recursive-agent 0.4.0

A minimal, orthogonal, self-improving coding agent kernel in Rust
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
//! Cross-turn agent wrapper.
//!
//! `AgentRunner` manages an `Agent` across multiple conversation turns,
//! preserving the transcript between turns and streaming events to the
//! caller. This is the extracted pattern from the REPL in `main.rs`,
//! made reusable for loop mode, HTTP API sessions, and TUI.

use std::sync::Arc;
use tokio::sync::mpsc;
use tokio::sync::Mutex;

use crate::agent::{Agent, AgentOutcome, StepEvent};
use crate::error::Result;
use crate::tools::BackgroundJobManager;

/// Manages an Agent across multiple conversation turns.
///
/// Preserves transcript between turns, emits events via a caller-provided
/// channel, and tracks cumulative turn count. Each call to `turn()` runs
/// the agent once with the given goal, then restores the transcript so the
/// next turn continues the conversation.
///
/// Optionally holds a reference to a shared `BackgroundJobManager`. When
/// `clear()` is called, any pending background jobs are also cleared.
///
/// # Example
///
/// ```ignore
/// let mut runner = AgentRunner::new(agent);
/// let (tx, mut rx) = mpsc::unbounded_channel();
///
/// // First turn
/// let outcome = runner.turn("Hello", Some(tx.clone())).await?;
///
/// // Second turn — transcript from turn 1 is preserved
/// let outcome = runner.turn("Follow up", Some(tx.clone())).await?;
///
/// // Start fresh
/// runner.clear();
/// ```
pub struct AgentRunner {
    agent: Agent,
    total_turns: usize,
    /// Optional shared background job manager. When set, `clear()` will
    /// also cancel all tracked background jobs.
    bg_manager: Option<Arc<Mutex<BackgroundJobManager>>>,
}

impl AgentRunner {
    /// Create a runner from a pre-built Agent.
    pub fn new(agent: Agent) -> Self {
        Self {
            agent,
            total_turns: 0,
            bg_manager: None,
        }
    }

    /// Create a runner that also manages background jobs.
    ///
    /// When `clear()` is called, all tracked background jobs are removed
    /// from the shared manager in addition to clearing the transcript.
    pub fn with_bg_manager(agent: Agent, bg_manager: Arc<Mutex<BackgroundJobManager>>) -> Self {
        Self {
            agent,
            total_turns: 0,
            bg_manager: Some(bg_manager),
        }
    }

    /// Run a single turn with the given goal.
    ///
    /// If `events` is `Some(sender)`, step events are streamed through the
    /// channel in real time. Pass `None` to suppress events.
    ///
    /// The transcript is automatically preserved for the next turn. Returns
    /// the outcome of this turn.
    pub async fn turn(
        &mut self,
        goal: impl Into<String>,
        events: Option<mpsc::UnboundedSender<StepEvent>>,
    ) -> Result<AgentOutcome> {
        self.agent.set_events(events);

        let outcome = self.agent.run(goal).await?;

        // Restore transcript for next turn (run() takes it via mem::take)
        self.agent.set_transcript(outcome.transcript.clone());
        self.agent.set_events(None);
        self.total_turns += 1;

        Ok(outcome)
    }

    /// Clear the conversation history and reset the turn counter.
    ///
    /// If a `BackgroundJobManager` was provided, all tracked background
    /// jobs are also removed.
    pub fn clear(&mut self) {
        self.agent.set_transcript(Vec::new());
        self.total_turns = 0;
        if let Some(ref mgr) = self.bg_manager {
            // Best-effort: if the lock is poisoned, we still clear the agent state.
            if let Ok(mut mgr) = mgr.try_lock() {
                mgr.clear();
            }
        }
    }

    /// Number of turns completed so far.
    pub fn turns(&self) -> usize {
        self.total_turns
    }

    /// Access the underlying agent (e.g., to call `confirm_plan`).
    pub fn agent(&self) -> &Agent {
        &self.agent
    }

    /// Mutable access to the underlying agent.
    pub fn agent_mut(&mut self) -> &mut Agent {
        &mut self.agent
    }

    /// Run a loop: execute turns until the agent stops scheduling wakeups.
    ///
    /// Between turns, sleeps for the requested `delay`. If the agent doesn't
    /// call `schedule_wakeup` during a turn, the loop ends.
    ///
    /// The `wakeup_slot` should be the same slot registered with the
    /// `ScheduleWakeup` tool in the agent's tool registry.
    pub async fn run_loop(
        &mut self,
        initial_goal: impl Into<String>,
        wakeup_slot: &crate::tools::WakeupSlot,
        events: Option<mpsc::UnboundedSender<StepEvent>>,
    ) -> Result<Vec<AgentOutcome>> {
        let mut outcomes = Vec::new();
        let mut next_goal = initial_goal.into();

        loop {
            let outcome = self.turn(&next_goal, events.clone()).await?;
            outcomes.push(outcome);

            // Check if the agent scheduled a wakeup
            let wakeup = wakeup_slot.lock().ok().and_then(|mut slot| slot.take());

            match wakeup {
                Some(req) => {
                    tokio::time::sleep(req.delay).await;
                    next_goal = req.prompt;
                }
                None => break, // No wakeup = loop ends
            }
        }
        Ok(outcomes)
    }

    /// Run a loop with background job awareness.
    ///
    /// After each turn, checks both:
    /// 1. The `WakeupSlot` for an explicit wakeup request (from `schedule_wakeup` tool)
    /// 2. The `BackgroundJobManager` for completed jobs
    ///
    /// If a background job completed, its output is injected as the next turn's
    /// goal. If a wakeup was scheduled, the runner sleeps for the requested
    /// delay then continues. If neither is present, the loop ends.
    ///
    /// The `wakeup_slot` should be the same slot registered with the
    /// `ScheduleWakeup` tool in the agent's tool registry.
    pub async fn run_event_loop(
        &mut self,
        initial_goal: impl Into<String>,
        wakeup_slot: &crate::tools::WakeupSlot,
        events: Option<mpsc::UnboundedSender<StepEvent>>,
    ) -> Result<Vec<AgentOutcome>> {
        let mut outcomes = Vec::new();
        let mut next_goal = initial_goal.into();

        loop {
            let outcome = self.turn(&next_goal, events.clone()).await?;
            outcomes.push(outcome);

            // Priority 1: explicit wakeup
            let wakeup = wakeup_slot
                .lock()
                .ok()
                .and_then(|mut slot| slot.take());
            if let Some(req) = wakeup {
                tokio::time::sleep(req.delay).await;
                next_goal = req.prompt;
                continue;
            }

            // Priority 2: background job completed
            if let Some(ref mgr) = self.bg_manager {
                if let Ok(mut mgr) = mgr.try_lock() {
                    if let Some((id, output)) = mgr.take_completed() {
                        next_goal = format!(
                            "Background job '{}' completed:\n{}",
                            id, output
                        );
                        continue;
                    }
                }
            }

            // Nothing to do → loop ends
            break;
        }
        Ok(outcomes)
    }
}

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

    use tokio::sync::mpsc;

    use crate::agent::StepEvent;
    use crate::llm::{Completion, MockProvider};
    use crate::message::{Message, Role};
    use crate::tools::ToolRegistry;
    use crate::Agent;

    use super::*;

    fn make_agent(script: Vec<Completion>) -> Agent {
        let provider = Arc::new(MockProvider::new(script));
        Agent::builder()
            .llm(provider)
            .tools(ToolRegistry::default())
            .system_prompt("You are a helpful assistant.")
            .max_steps(5)
            .build()
            .unwrap()
    }

    fn user_content(msg: &Message) -> Option<&str> {
        if msg.role == Role::User {
            Some(msg.content.as_str())
        } else {
            None
        }
    }

    #[tokio::test]
    async fn preserves_transcript_across_turns() {
        let script = vec![
            Completion {
                content: "First response".into(),
                tool_calls: vec![],
                finish_reason: Some("stop".to_string()),
                usage: None,
                reasoning_content: None,
            },
            Completion {
                content: "Second response".into(),
                tool_calls: vec![],
                finish_reason: Some("stop".to_string()),
                usage: None,
                reasoning_content: None,
            },
        ];
        let agent = make_agent(script);
        let mut runner = AgentRunner::new(agent);

        let outcome1 = runner.turn("First goal", None).await.unwrap();
        assert_eq!(runner.turns(), 1);
        assert!(outcome1
            .transcript
            .iter()
            .any(|m| { m.role == Role::User && m.content == "First goal" }));

        let outcome2 = runner.turn("Second goal", None).await.unwrap();
        assert_eq!(runner.turns(), 2);

        // Second turn's transcript should contain messages from both turns
        let texts: Vec<&str> = outcome2
            .transcript
            .iter()
            .filter_map(user_content)
            .collect();
        assert!(
            texts.contains(&"First goal"),
            "first turn goal should be in transcript: {texts:?}"
        );
        assert!(
            texts.contains(&"Second goal"),
            "second turn goal should be in transcript: {texts:?}"
        );
    }

    #[tokio::test]
    async fn clear_resets_transcript() {
        // Provide two completions: one for the first turn, one for after clear
        let script = vec![
            Completion {
                content: "Response".into(),
                tool_calls: vec![],
                finish_reason: Some("stop".to_string()),
                usage: None,
                reasoning_content: None,
            },
            Completion {
                content: "After clear".into(),
                tool_calls: vec![],
                finish_reason: Some("stop".to_string()),
                usage: None,
                reasoning_content: None,
            },
        ];
        let agent = make_agent(script);
        let mut runner = AgentRunner::new(agent);

        runner.turn("Goal", None).await.unwrap();
        assert_eq!(runner.turns(), 1);

        runner.clear();
        assert_eq!(runner.turns(), 0);

        // After clear, the agent should have no transcript
        let agent = runner.agent();
        // Verify the agent's internal state is reset by running another turn
        // and checking it only has the new goal.
        let _ = agent;
        let outcome = runner.turn("New goal", None).await.unwrap();
        let user_msgs: Vec<&str> = outcome.transcript.iter().filter_map(user_content).collect();
        assert_eq!(user_msgs, vec!["New goal"]);
    }

    #[tokio::test]
    async fn turns_increments() {
        let script = vec![
            Completion {
                content: "One".into(),
                tool_calls: vec![],
                finish_reason: Some("stop".to_string()),
                usage: None,
                reasoning_content: None,
            },
            Completion {
                content: "Two".into(),
                tool_calls: vec![],
                finish_reason: Some("stop".to_string()),
                usage: None,
                reasoning_content: None,
            },
            Completion {
                content: "Three".into(),
                tool_calls: vec![],
                finish_reason: Some("stop".to_string()),
                usage: None,
                reasoning_content: None,
            },
        ];
        let agent = make_agent(script);
        let mut runner = AgentRunner::new(agent);

        assert_eq!(runner.turns(), 0);
        runner.turn("A", None).await.unwrap();
        assert_eq!(runner.turns(), 1);
        runner.turn("B", None).await.unwrap();
        assert_eq!(runner.turns(), 2);
        runner.turn("C", None).await.unwrap();
        assert_eq!(runner.turns(), 3);
    }

    #[tokio::test]
    async fn events_forwarded_when_provided() {
        let script = vec![Completion {
            content: "Hello world".into(),
            tool_calls: vec![],
            finish_reason: Some("stop".to_string()),
            usage: None,
            reasoning_content: None,
        }];
        let agent = make_agent(script);
        let mut runner = AgentRunner::new(agent);

        let (tx, mut rx) = mpsc::unbounded_channel();
        runner.turn("Goal", Some(tx)).await.unwrap();

        // We should have received events (at least a Finished event)
        let events: Vec<StepEvent> = {
            let mut v = Vec::new();
            while let Ok(ev) = rx.try_recv() {
                v.push(ev);
            }
            v
        };
        assert!(!events.is_empty(), "should have received events");
        assert!(
            events
                .iter()
                .any(|e| matches!(e, StepEvent::Finished { .. })),
            "should have a Finished event"
        );
    }

    #[tokio::test]
    async fn no_events_when_none_passed() {
        let script = vec![Completion {
            content: "Silent".into(),
            tool_calls: vec![],
            finish_reason: Some("stop".to_string()),
            usage: None,
            reasoning_content: None,
        }];
        let agent = make_agent(script);
        let mut runner = AgentRunner::new(agent);

        runner.turn("Goal", None).await.unwrap();

        // The agent's events channel should be None
        // We verify by checking that no events were emitted
        // (we can't inspect the agent's events field directly,
        // but we can confirm the turn completed successfully)
        assert_eq!(runner.turns(), 1);
    }

    #[tokio::test]
    async fn agent_accessors_work() {
        let script = vec![Completion {
            content: "Test".into(),
            tool_calls: vec![],
            finish_reason: Some("stop".to_string()),
            usage: None,
            reasoning_content: None,
        }];
        let agent = make_agent(script);
        let mut runner = AgentRunner::new(agent);

        // Immutable access
        let _agent_ref = runner.agent();
        // Mutable access
        let _agent_mut = runner.agent_mut();
    }

    #[tokio::test]
    async fn run_event_loop_triggers_on_wakeup() {
        use std::sync::Mutex as StdMutex;
        use crate::tools::WakeupSlot;

        let script = vec![
            Completion {
                content: "Turn 1".into(),
                tool_calls: vec![],
                finish_reason: Some("stop".to_string()),
                usage: None,
                reasoning_content: None,
            },
            Completion {
                content: "Turn 2".into(),
                tool_calls: vec![],
                finish_reason: Some("stop".to_string()),
                usage: None,
                reasoning_content: None,
            },
        ];
        let agent = make_agent(script);
        let mut runner = AgentRunner::new(agent);
        let wakeup_slot: WakeupSlot = Arc::new(StdMutex::new(None));

        // Pre-seed a wakeup so the loop runs a second turn
        {
            let mut slot = wakeup_slot.lock().unwrap();
            *slot = Some(crate::tools::WakeupRequest {
                delay: std::time::Duration::from_millis(1),
                reason: "continue".into(),
                prompt: "Second goal".into(),
            });
        }

        let outcomes = runner
            .run_event_loop("First goal", &wakeup_slot, None)
            .await
            .unwrap();

        assert_eq!(outcomes.len(), 2, "should have run 2 turns");
        assert_eq!(runner.turns(), 2);
    }

    #[tokio::test]
    async fn run_event_loop_ends_when_no_wakeup_or_bg() {
        let script = vec![Completion {
            content: "Only turn".into(),
            tool_calls: vec![],
            finish_reason: Some("stop".to_string()),
            usage: None,
            reasoning_content: None,
        }];
        let agent = make_agent(script);
        let mut runner = AgentRunner::new(agent);
        let wakeup_slot = Arc::new(std::sync::Mutex::new(None));

        let outcomes = runner
            .run_event_loop("Single goal", &wakeup_slot, None)
            .await
            .unwrap();

        assert_eq!(outcomes.len(), 1, "should have run exactly 1 turn");
        assert_eq!(runner.turns(), 1);
    }

    #[tokio::test]
    async fn run_event_loop_triggers_on_bg_completion() {
        use std::sync::Mutex as StdMutex;
        use crate::tools::WakeupSlot;

        let script = vec![
            Completion {
                content: "Turn 1".into(),
                tool_calls: vec![],
                finish_reason: Some("stop".to_string()),
                usage: None,
                reasoning_content: None,
            },
            Completion {
                content: "Turn 2".into(),
                tool_calls: vec![],
                finish_reason: Some("stop".to_string()),
                usage: None,
                reasoning_content: None,
            },
        ];
        let agent = make_agent(script);
        let bg_manager = Arc::new(Mutex::new(BackgroundJobManager::new()));
        let mut runner = AgentRunner::with_bg_manager(agent, bg_manager.clone());
        let wakeup_slot: WakeupSlot = Arc::new(StdMutex::new(None));

        // Pre-seed a completed background job
        {
            let mut mgr = bg_manager.lock().await;
            mgr.insert(crate::tools::run_background::Job {
                state: crate::tools::run_background::JobState::Completed {
                    stdout: "build succeeded".into(),
                    stderr: "".into(),
                    exit_code: 0,
                },
                created_at: std::time::Instant::now(),
            });
        }

        let outcomes = runner
            .run_event_loop("First goal", &wakeup_slot, None)
            .await
            .unwrap();

        assert_eq!(outcomes.len(), 2, "should have run 2 turns (initial + bg trigger)");
        assert_eq!(runner.turns(), 2);
    }
}