bob-runtime 0.3.2

Runtime orchestration layer for Bob Agent Framework
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
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
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
//! # Typestate Agent Runner
//!
//! Exposes the agent turn FSM as an explicit typestate machine, enabling:
//!
//! - **Step-by-step execution**: developers can manually advance the agent
//! - **Human-in-the-loop**: pause before tool execution for approval
//! - **Distributed suspend/resume**: serialize state between steps
//! - **Compile-time safety**: invalid state transitions are rejected at build time
//!
//! ## State Machine
//!
//! ```text
//! Ready ──infer()──▶ AwaitingToolCall
//!   │                     │
//!   │                     ├──provide_tool_results()──▶ Ready
//!   │                     │
//!   │                     └──require_approval()──▶ AwaitingApproval
//!   │                                                  │
//!   │                                                  ├──approve()──▶ AwaitingToolCall
//!   │                                                  │
//!   │                                                  └──deny()──▶ Finished
//!//!   └──infer()──▶ Finished (when no tool calls)
//! ```
//!
//! ## Example
//!
//! ```rust,ignore
//! use bob_runtime::typestate::*;
//!
//! // High-level: run to completion
//! let result = AgentRunner::new(context, llm, tools)
//!     .run_to_completion()
//!     .await?;
//!
//! // Low-level: step-by-step control
//! let runner = AgentRunner::new(context, llm, tools);
//! let step = runner.infer().await?;
//! match step {
//!     AgentStepResult::Finished(runner) => {
//!         println!("done: {}", runner.response().content);
//!     }
//!     AgentStepResult::RequiresTool(runner) => {
//!         // Human-in-the-loop: ask for approval
//!         let results = execute_tools_with_approval(runner.pending_calls()).await;
//!         let runner = runner.provide_tool_results(results);
//!         // Continue to next step...
//!     }
//! }
//! ```

use bob_core::{
    error::AgentError,
    ports::{ContextCompactorPort, LlmPort, SessionStore, ToolPort},
    types::{
        AgentResponse, FinishReason, LlmRequest, Message, Role, SessionState, TokenUsage, ToolCall,
        ToolResult, TurnPolicy,
    },
};

// ── State Markers ────────────────────────────────────────────────────

/// Agent is ready to perform LLM inference.
///
/// This is the initial state and the state after tool results are provided.
/// Only valid transitions: `infer()` → `AwaitingToolCall` or `Finished`.
#[derive(Debug)]
pub struct Ready;

/// Agent has requested tool calls and is waiting for results.
///
/// This state holds the pending tool calls that need to be executed.
/// Valid transitions:
/// - `provide_tool_results()` → `Ready` (continue execution)
/// - `require_approval()` → `AwaitingApproval` (human-in-the-loop)
/// - `cancel()` → `Finished` (abort execution)
#[derive(Debug)]
pub struct AwaitingToolCall {
    /// Pending tool calls requested by the LLM.
    pub pending_calls: Vec<ToolCall>,
    /// Native tool call IDs (if using provider-native tool calling).
    pub call_ids: Vec<Option<String>>,
}

/// Agent is waiting for human approval before executing tool calls.
///
/// This state is entered when `require_approval()` is called on
/// `AwaitingToolCall`. It provides compile-time safety by preventing
/// direct tool execution without explicit approval.
///
/// Valid transitions:
/// - `approve()` → `AwaitingToolCall` (proceed with execution)
/// - `deny()` → `Finished` (abort with reason)
#[derive(Debug)]
pub struct AwaitingApproval {
    /// Pending tool calls awaiting approval.
    pub pending_calls: Vec<ToolCall>,
    /// Native tool call IDs.
    pub call_ids: Vec<Option<String>>,
    /// Reason for requiring approval (for audit trail).
    pub reason: String,
}

/// Agent has finished execution with a final response.
///
/// Terminal state — no further transitions are possible.
/// Access the final response via `response()` or `into_response()`.
#[derive(Debug)]
pub struct Finished {
    /// The final agent response.
    pub response: AgentResponse,
}

// ── Agent Runner ─────────────────────────────────────────────────────

/// Typestate-parameterized agent runner.
///
/// The type parameter `S` encodes the current FSM state:
/// - [`Ready`] — can call [`infer`](AgentRunner<Ready>::infer)
/// - [`AwaitingToolCall`] — can call
///   [`provide_tool_results`](AgentRunner<AwaitingToolCall>::provide_tool_results)
/// - [`Finished`] — can access the final [`response`](AgentRunner<Finished>::response)
#[derive(Debug)]
pub struct AgentRunner<S> {
    state: S,
    session: SessionState,
    context: RunnerContext,
}

/// Immutable execution context carried through the typestate machine.
#[derive(Debug, Clone)]
pub struct RunnerContext {
    pub session_id: String,
    pub model: String,
    pub system_instructions: String,
    pub policy: TurnPolicy,
    pub steps_taken: u32,
    pub tool_calls_made: u32,
    pub total_usage: TokenUsage,
    pub tool_transcript: Vec<ToolResult>,
}

/// Result of an inference step — either finished or needs tools.
pub enum AgentStepResult {
    /// Agent produced a final response.
    Finished(AgentRunner<Finished>),
    /// Agent requested tool calls that need to be executed.
    RequiresTool(AgentRunner<AwaitingToolCall>),
}

impl std::fmt::Debug for AgentStepResult {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Finished(_) => f.write_str("AgentStepResult::Finished"),
            Self::RequiresTool(_) => f.write_str("AgentStepResult::RequiresTool"),
        }
    }
}

// ── Ready State ──────────────────────────────────────────────────────

impl AgentRunner<Ready> {
    /// Create a new runner in the `Ready` state.
    #[must_use]
    pub fn new(
        session_id: impl Into<String>,
        model: impl Into<String>,
        system_instructions: impl Into<String>,
        policy: TurnPolicy,
        session: SessionState,
    ) -> Self {
        Self {
            state: Ready,
            session,
            context: RunnerContext {
                session_id: session_id.into(),
                model: model.into(),
                system_instructions: system_instructions.into(),
                policy,
                steps_taken: 0,
                tool_calls_made: 0,
                total_usage: TokenUsage::default(),
                tool_transcript: Vec::new(),
            },
        }
    }

    /// Perform LLM inference and transition to the next state.
    ///
    /// Returns [`AgentStepResult::Finished`] if the LLM produces a final
    /// response, or [`AgentStepResult::RequiresTool`] if tool calls are
    /// needed.
    ///
    /// # Errors
    ///
    /// Returns an error if the LLM call fails or policy limits are exceeded.
    pub async fn infer(
        mut self,
        llm: &(impl LlmPort + ?Sized),
        tools: &(impl ToolPort + ?Sized),
        compactor: &(impl ContextCompactorPort + ?Sized),
    ) -> Result<AgentStepResult, AgentError> {
        if self.context.steps_taken >= self.context.policy.max_steps {
            return Ok(AgentStepResult::Finished(AgentRunner {
                state: Finished {
                    response: AgentResponse {
                        content: "Max steps exceeded.".to_string(),
                        tool_transcript: self.context.tool_transcript.clone(),
                        usage: self.context.total_usage.clone(),
                        finish_reason: FinishReason::GuardExceeded,
                    },
                },
                session: self.session,
                context: self.context,
            }));
        }

        let tool_descriptors = tools.list_tools().await.unwrap_or_default();
        let messages = compactor.compact(&self.session).await;

        let request = LlmRequest {
            model: self.context.model.clone(),
            messages,
            tools: tool_descriptors,
            output_schema: None,
        };

        let response = llm.complete(request).await?;

        self.context.steps_taken += 1;
        self.context.total_usage.prompt_tokens =
            self.context.total_usage.prompt_tokens.saturating_add(response.usage.prompt_tokens);
        self.context.total_usage.completion_tokens = self
            .context
            .total_usage
            .completion_tokens
            .saturating_add(response.usage.completion_tokens);

        if response.tool_calls.is_empty() {
            let assistant_msg = Message::text(Role::Assistant, response.content.clone());
            self.session.messages.push(assistant_msg);

            Ok(AgentStepResult::Finished(AgentRunner {
                state: Finished {
                    response: AgentResponse {
                        content: response.content,
                        tool_transcript: self.context.tool_transcript.clone(),
                        usage: self.context.total_usage.clone(),
                        finish_reason: FinishReason::Stop,
                    },
                },
                session: self.session,
                context: self.context,
            }))
        } else {
            let call_ids: Vec<Option<String>> =
                response.tool_calls.iter().map(|c| c.call_id.clone()).collect();

            let assistant_msg =
                Message::assistant_tool_calls(response.content, response.tool_calls.clone());
            self.session.messages.push(assistant_msg);

            Ok(AgentStepResult::RequiresTool(AgentRunner {
                state: AwaitingToolCall { pending_calls: response.tool_calls, call_ids },
                session: self.session,
                context: self.context,
            }))
        }
    }

    /// Run the agent loop until completion (high-level convenience method).
    ///
    /// This is equivalent to calling [`infer`](Self::infer) in a loop until
    /// a [`Finished`] state is reached.
    ///
    /// # Errors
    ///
    /// Returns an error if any LLM call fails.
    pub async fn run_to_completion(
        self,
        llm: &(impl LlmPort + ?Sized),
        tools: &(impl ToolPort + ?Sized),
        compactor: &(impl ContextCompactorPort + ?Sized),
        store: &(impl SessionStore + ?Sized),
    ) -> Result<AgentRunner<Finished>, AgentError> {
        let mut current = self.infer(llm, tools, compactor).await?;

        loop {
            match current {
                AgentStepResult::Finished(runner) => {
                    store.save(&runner.context.session_id, &runner.session).await?;
                    return Ok(runner);
                }
                AgentStepResult::RequiresTool(runner) => {
                    let mut results = Vec::new();
                    for call in &runner.state.pending_calls {
                        match tools.call_tool(call.clone()).await {
                            Ok(result) => results.push(result),
                            Err(err) => results.push(ToolResult {
                                name: call.name.clone(),
                                output: serde_json::json!({"error": err.to_string()}),
                                is_error: true,
                            }),
                        }
                    }
                    let ready = runner.provide_tool_results(results);
                    current = ready.infer(llm, tools, compactor).await?;
                }
            }
        }
    }
}

// ── AwaitingToolCall State ───────────────────────────────────────────

impl AgentRunner<AwaitingToolCall> {
    /// Get the pending tool calls that need to be executed.
    #[must_use]
    pub fn pending_calls(&self) -> &[ToolCall] {
        &self.state.pending_calls
    }

    /// Provide tool execution results and transition back to `Ready`.
    ///
    /// The results must correspond 1:1 with the pending calls in the
    /// same order.
    #[must_use]
    pub fn provide_tool_results(mut self, results: Vec<ToolResult>) -> AgentRunner<Ready> {
        for (result, call_id) in results.iter().zip(self.state.call_ids.iter()) {
            let output_str = serde_json::to_string(&result.output).unwrap_or_default();
            self.session.messages.push(Message::tool_result(
                result.name.clone(),
                call_id.clone(),
                output_str,
            ));
            self.context.tool_calls_made += 1;
            self.context.tool_transcript.push(result.clone());
        }

        AgentRunner { state: Ready, session: self.session, context: self.context }
    }

    /// Cancel the pending tool calls and transition to `Finished`.
    #[must_use]
    pub fn cancel(self, reason: impl Into<String>) -> AgentRunner<Finished> {
        AgentRunner {
            state: Finished {
                response: AgentResponse {
                    content: reason.into(),
                    tool_transcript: self.context.tool_transcript.clone(),
                    usage: self.context.total_usage.clone(),
                    finish_reason: FinishReason::Cancelled,
                },
            },
            session: self.session,
            context: self.context,
        }
    }

    /// Require human approval before executing tool calls.
    ///
    /// Transitions to `AwaitingApproval` state, which prevents
    /// direct tool execution. Callers must explicitly `approve()`
    /// or `deny()` to proceed.
    ///
    /// This provides compile-time safety: `AwaitingToolCall` can
    /// directly execute tools via `provide_tool_results()`, but
    /// `AwaitingApproval` cannot — it must go through the approval
    /// gate first.
    #[must_use]
    pub fn require_approval(self, reason: impl Into<String>) -> AgentRunner<AwaitingApproval> {
        AgentRunner {
            state: AwaitingApproval {
                pending_calls: self.state.pending_calls,
                call_ids: self.state.call_ids,
                reason: reason.into(),
            },
            session: self.session,
            context: self.context,
        }
    }
}

// ── AwaitingApproval State ───────────────────────────────────────────

impl AgentRunner<AwaitingApproval> {
    /// Get the pending tool calls awaiting approval.
    #[must_use]
    pub fn pending_calls(&self) -> &[ToolCall] {
        &self.state.pending_calls
    }

    /// Get the reason approval was required.
    #[must_use]
    pub fn approval_reason(&self) -> &str {
        &self.state.reason
    }

    /// Approve the tool calls and transition back to `AwaitingToolCall`.
    ///
    /// After approval, call `provide_tool_results()` with the execution
    /// results to continue the agent loop.
    #[must_use]
    pub fn approve(self) -> AgentRunner<AwaitingToolCall> {
        AgentRunner {
            state: AwaitingToolCall {
                pending_calls: self.state.pending_calls,
                call_ids: self.state.call_ids,
            },
            session: self.session,
            context: self.context,
        }
    }

    /// Deny the tool calls and transition to `Finished`.
    ///
    /// The provided reason will be included in the final response
    /// for the user/audit trail.
    #[must_use]
    pub fn deny(self, reason: impl Into<String>) -> AgentRunner<Finished> {
        AgentRunner {
            state: Finished {
                response: AgentResponse {
                    content: reason.into(),
                    tool_transcript: self.context.tool_transcript.clone(),
                    usage: self.context.total_usage.clone(),
                    finish_reason: FinishReason::Cancelled,
                },
            },
            session: self.session,
            context: self.context,
        }
    }
}

// ── Finished State ───────────────────────────────────────────────────

impl AgentRunner<Finished> {
    /// Get a reference to the final response.
    #[must_use]
    pub fn response(&self) -> &AgentResponse {
        &self.state.response
    }

    /// Consume the runner and return the final response.
    #[must_use]
    pub fn into_response(self) -> AgentResponse {
        self.state.response
    }

    /// Get the final session state (for persistence).
    #[must_use]
    pub fn session(&self) -> &SessionState {
        &self.session
    }

    /// Get the execution context with usage stats.
    #[must_use]
    pub fn context(&self) -> &RunnerContext {
        &self.context
    }
}

// ── Tests ────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use bob_core::types::ToolDescriptor;

    use super::*;

    struct StubLlm;

    impl StubLlm {
        fn finish_response(content: &str) -> bob_core::types::LlmResponse {
            bob_core::types::LlmResponse {
                content: content.to_string(),
                usage: TokenUsage::default(),
                finish_reason: FinishReason::Stop,
                tool_calls: Vec::new(),
            }
        }
    }

    #[async_trait::async_trait]
    impl LlmPort for StubLlm {
        async fn complete(
            &self,
            _req: LlmRequest,
        ) -> Result<bob_core::types::LlmResponse, bob_core::error::LlmError> {
            Ok(Self::finish_response("done"))
        }

        async fn complete_stream(
            &self,
            _req: LlmRequest,
        ) -> Result<bob_core::types::LlmStream, bob_core::error::LlmError> {
            Err(bob_core::error::LlmError::Provider("not implemented".into()))
        }
    }

    struct StubTools;

    #[async_trait::async_trait]
    impl ToolPort for StubTools {
        async fn list_tools(&self) -> Result<Vec<ToolDescriptor>, bob_core::error::ToolError> {
            Ok(vec![])
        }

        async fn call_tool(
            &self,
            call: ToolCall,
        ) -> Result<ToolResult, bob_core::error::ToolError> {
            Ok(ToolResult { name: call.name, output: serde_json::json!(null), is_error: false })
        }
    }

    struct StubCompactor;

    #[async_trait::async_trait]
    impl ContextCompactorPort for StubCompactor {
        async fn compact(&self, session: &SessionState) -> Vec<Message> {
            session.messages.clone()
        }
    }

    struct StubStore;

    #[async_trait::async_trait]
    impl SessionStore for StubStore {
        async fn load(
            &self,
            _id: &bob_core::types::SessionId,
        ) -> Result<Option<SessionState>, bob_core::error::StoreError> {
            Ok(None)
        }

        async fn save(
            &self,
            _id: &bob_core::types::SessionId,
            _state: &SessionState,
        ) -> Result<(), bob_core::error::StoreError> {
            Ok(())
        }
    }

    #[tokio::test]
    async fn ready_infer_to_finished() {
        let runner = AgentRunner::new(
            "test-session",
            "test-model",
            "You are a test assistant.",
            TurnPolicy::default(),
            SessionState::default(),
        );

        let result = runner.infer(&StubLlm, &StubTools, &StubCompactor).await;
        assert!(result.is_ok(), "infer should succeed");

        if let Ok(AgentStepResult::Finished(runner)) = result {
            assert_eq!(runner.response().content, "done");
            assert_eq!(runner.response().finish_reason, FinishReason::Stop);
        } else {
            panic!("expected Finished result");
        }
    }

    #[tokio::test]
    async fn run_to_completion() {
        let runner = AgentRunner::new(
            "test-session",
            "test-model",
            "You are a test assistant.",
            TurnPolicy::default(),
            SessionState::default(),
        );

        let result =
            runner.run_to_completion(&StubLlm, &StubTools, &StubCompactor, &StubStore).await;
        assert!(result.is_ok(), "run_to_completion should succeed");

        let finished = result.unwrap();
        assert_eq!(finished.response().content, "done");
    }

    #[test]
    fn awaiting_tool_call_provide_results() {
        let runner = AgentRunner {
            state: AwaitingToolCall {
                pending_calls: vec![ToolCall::new("test", serde_json::json!({}))],
                call_ids: vec![Some("call-1".into())],
            },
            session: SessionState::default(),
            context: RunnerContext {
                session_id: "test".into(),
                model: "test".into(),
                system_instructions: String::new(),
                policy: TurnPolicy::default(),
                steps_taken: 1,
                tool_calls_made: 0,
                total_usage: TokenUsage::default(),
                tool_transcript: Vec::new(),
            },
        };

        let results = vec![ToolResult {
            name: "test".into(),
            output: serde_json::json!({"ok": true}),
            is_error: false,
        }];

        let ready = runner.provide_tool_results(results);
        assert_eq!(ready.context.tool_calls_made, 1);
        assert_eq!(ready.session.messages.len(), 1);
    }
}