behest-core 0.5.9

Core types for the behest agent runtime: messages, errors, tool definitions, and sans-IO run state machine
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
//! Sans-IO run state machine for the agent prompt loop.
//!
//! The run loop is modeled as a pure state machine that receives input events,
//! transitions between states, and produces output actions. This design is:
//!
//! - **Runtime-agnostic**: no dependency on tokio or any async runtime.
//! - **Serializable**: the entire machine state can be serialized for
//!   checkpoint/resume across process boundaries.
//! - **Testable**: transitions can be verified without network, model API,
//!   or actual tool execution.
//!
//! The [`transition`] function is the core: `(state, input, config) -> (new_state, actions)`.

use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::message::{ChatRequest, ContentPart, FinishReason, Message, TokenUsage};
use crate::tool_types::ToolCall;

/// Shared cancellation message to avoid string duplication.
const CANCELLED_MSG: &str = "cancelled";

/// The state of a single agent run.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum RunState {
    /// Initial state, ready to accept a user message.
    Idle,
    /// Building the context (system prompt, history, RAG) for the model call.
    BuildingContext,
    /// Waiting for the model to respond (non-streaming).
    CallingModel,
    /// Receiving streaming chunks from the model.
    StreamingModel,
    /// Processing the completed model response.
    ProcessingResponse,
    /// Executing tool calls requested by the model.
    ExecutingTools,
    /// Waiting for human approval of a tool call.
    WaitingApproval,
    /// Compacting conversation memory.
    Compacting,
    /// Demoting old messages to long-term storage.
    Demoting,
    /// Run completed successfully.
    Finished,
    /// Run was aborted due to an error or cancellation.
    Aborted,
}

/// Input events that drive the state machine forward.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum RunInput {
    /// A user message has been received.
    UserMessageReceived {
        /// Content parts of the user message.
        content: Vec<ContentPart>,
    },
    /// A streaming text chunk was received from the model.
    ModelChunkReceived {
        /// Incremental text delta.
        delta: String,
    },
    /// The model completed its response (non-streaming or end of stream).
    ModelCompleted {
        /// The complete assistant message.
        message: Message,
        /// Token usage for this model call.
        usage: TokenUsage,
    },
    /// Tool calls were requested by the model.
    ToolCallRequested {
        /// The tool calls to execute.
        calls: Vec<ToolCall>,
    },
    /// A tool execution completed.
    ToolResultReceived {
        /// The call ID this result corresponds to.
        call_id: String,
        /// The tool output.
        output: Value,
    },
    /// Human approval was granted for a pending tool call.
    ToolApprovalGranted {
        /// The call ID that was approved.
        call_id: String,
    },
    /// Human approval was rejected for a pending tool call.
    ToolApprovalRejected {
        /// The call ID that was rejected.
        call_id: String,
        /// Optional reason for rejection.
        reason: Option<String>,
    },
    /// Memory compaction completed.
    MemoryCompactionCompleted {
        /// Summary text produced by the compactor.
        summary: String,
    },
    /// A runtime-level error occurred.
    RuntimeErrorReceived {
        /// Description of the error.
        error: String,
    },
    /// Cancellation was requested.
    CancellationRequested,
}

/// Actions produced by the state machine that must be executed by the runtime.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum RunAction {
    /// Request a model completion (non-streaming or streaming).
    RequestModel {
        /// The chat request to send.
        request: ChatRequest,
    },
    /// Execute one or more tool calls.
    ExecuteTool {
        /// The tool calls to execute.
        calls: Vec<ToolCall>,
    },
    /// Request human approval before executing a tool.
    RequestToolApproval {
        /// The tool call requiring approval.
        call: ToolCall,
        /// Human-readable reason approval is needed.
        reason: String,
    },
    /// Compact conversation memory (summarize old messages).
    CompactMemory,
    /// Demote old messages to long-term storage.
    DemoteMemory,
    /// The run has finished.
    FinishRun {
        /// Reason for finishing.
        reason: FinishReason,
        /// Total token usage for the run.
        usage: TokenUsage,
    },
    /// The run was aborted.
    AbortRun {
        /// Error that caused the abort.
        error: String,
    },
    /// No action needed (e.g., during streaming).
    Noop,
}

/// Configuration for the run state machine.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RunConfig {
    /// Maximum number of tool-calling iterations (model → tool → model loops).
    pub max_iterations: usize,
    /// Maximum total tokens across all model calls.
    pub max_tokens: Option<usize>,
    /// Whether to continue when a tool fails.
    pub continue_on_tool_failure: bool,
}

impl Default for RunConfig {
    fn default() -> Self {
        Self {
            max_iterations: 10,
            max_tokens: None,
            continue_on_tool_failure: true,
        }
    }
}

/// The core transition function.
///
/// Given the current state, an input event, and configuration, returns the next
/// state and the actions the runtime should execute.
///
/// # Determinism
///
/// This function is pure: for the same `(state, input, config)`, it always
/// produces the same `(next_state, actions)`. This property enables:
/// - Deterministic replay from event logs
/// - Snapshot-based crash recovery
/// - Property-based testing
#[must_use]
pub fn transition(
    state: &RunState,
    input: RunInput,
    _config: &RunConfig,
) -> (RunState, Vec<RunAction>) {
    match (state, input) {
        // ---- Idle ----
        (RunState::Idle, RunInput::UserMessageReceived { .. }) => {
            (RunState::BuildingContext, vec![RunAction::Noop])
        }
        (RunState::Idle, RunInput::CancellationRequested) => (
            RunState::Aborted,
            vec![RunAction::AbortRun {
                error: "cancelled before start".to_string(),
            }],
        ),

        // ---- BuildingContext ----
        (RunState::BuildingContext, RunInput::UserMessageReceived { .. }) => {
            // Context built implicitly by the runtime adapter; transition to model call.
            // The runtime adapter constructs the ChatRequest and feeds it back.
            (RunState::CallingModel, vec![RunAction::Noop])
        }

        // ---- CallingModel ----
        (RunState::CallingModel, RunInput::ModelChunkReceived { .. }) => {
            (RunState::StreamingModel, vec![RunAction::Noop])
        }
        (RunState::CallingModel, RunInput::ModelCompleted { message, usage: _ }) => {
            if !message.tool_calls().is_empty() {
                let calls = message.tool_calls().to_vec();
                (
                    RunState::ExecutingTools,
                    vec![RunAction::ExecuteTool { calls }],
                )
            } else {
                (
                    RunState::Finished,
                    vec![RunAction::FinishRun {
                        reason: FinishReason::Stop,
                        usage: TokenUsage::new(0, 0),
                    }],
                )
            }
        }
        (RunState::CallingModel, RunInput::RuntimeErrorReceived { error }) => {
            (RunState::Aborted, vec![RunAction::AbortRun { error }])
        }
        (RunState::CallingModel, RunInput::CancellationRequested) => (
            RunState::Aborted,
            vec![RunAction::AbortRun {
                error: CANCELLED_MSG.to_string(),
            }],
        ),

        // ---- StreamingModel ----
        (RunState::StreamingModel, RunInput::ModelChunkReceived { .. }) => {
            (RunState::StreamingModel, vec![RunAction::Noop])
        }
        (RunState::StreamingModel, RunInput::ModelCompleted { message, usage }) => {
            if !message.tool_calls().is_empty() {
                let calls = message.tool_calls().to_vec();
                (
                    RunState::ExecutingTools,
                    vec![RunAction::ExecuteTool { calls }],
                )
            } else {
                (
                    RunState::Finished,
                    vec![RunAction::FinishRun {
                        reason: FinishReason::Stop,
                        usage,
                    }],
                )
            }
        }
        (RunState::StreamingModel, RunInput::RuntimeErrorReceived { error }) => {
            (RunState::Aborted, vec![RunAction::AbortRun { error }])
        }
        (RunState::StreamingModel, RunInput::CancellationRequested) => (
            RunState::Aborted,
            vec![RunAction::AbortRun {
                error: CANCELLED_MSG.to_string(),
            }],
        ),

        // ---- ProcessingResponse ----
        (RunState::ProcessingResponse, RunInput::ToolCallRequested { calls }) => (
            RunState::ExecutingTools,
            vec![RunAction::ExecuteTool { calls }],
        ),

        // ---- ExecutingTools ----
        (RunState::ExecutingTools, RunInput::ToolResultReceived { .. }) => {
            // After all tools complete, the runtime adapter should transition
            // back to BuildingContext for the next model call.
            // Individual tool results are collected by the runtime.
            (RunState::ExecutingTools, vec![RunAction::Noop])
        }
        (RunState::ExecutingTools, RunInput::RuntimeErrorReceived { .. }) => {
            (RunState::BuildingContext, vec![RunAction::Noop])
        }

        // ---- WaitingApproval ----
        (RunState::WaitingApproval, RunInput::ToolApprovalGranted { call_id }) => (
            RunState::ExecutingTools,
            vec![RunAction::ExecuteTool {
                calls: vec![ToolCall::new(call_id, String::new(), Value::Null)],
            }],
        ),
        (RunState::WaitingApproval, RunInput::ToolApprovalRejected { call_id: _, reason }) => {
            // Tool was rejected; feed rejection back to the model
            let _error_msg = reason.unwrap_or_else(|| "tool execution was rejected".to_string());
            (RunState::BuildingContext, vec![RunAction::Noop])
        }

        // ---- Compacting ----
        (RunState::Compacting, RunInput::MemoryCompactionCompleted { .. }) => {
            (RunState::BuildingContext, vec![RunAction::Noop])
        }

        // ---- Terminal states ----
        (RunState::Finished, _) | (RunState::Aborted, _) => {
            // No transitions from terminal states
            (state.clone(), vec![])
        }

        // ---- Catch-all for unhandled combinations ----
        _ => (state.clone(), vec![RunAction::Noop]),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::message::ContentPart;

    fn make_config() -> RunConfig {
        RunConfig::default()
    }

    #[test]
    fn idle_to_building_context_on_user_message() {
        let (next, actions) = transition(
            &RunState::Idle,
            RunInput::UserMessageReceived {
                content: vec![ContentPart::text("hello")],
            },
            &make_config(),
        );
        assert_eq!(next, RunState::BuildingContext);
        assert!(matches!(actions.as_slice(), [RunAction::Noop]));
    }

    #[test]
    fn idle_cancellation_aborts() {
        let (next, actions) = transition(
            &RunState::Idle,
            RunInput::CancellationRequested,
            &make_config(),
        );
        assert_eq!(next, RunState::Aborted);
        assert!(matches!(actions.as_slice(), [RunAction::AbortRun { .. }]));
    }

    #[test]
    fn calling_model_with_tool_calls_transitions_to_executing() {
        let msg = Message::Assistant {
            content: vec![],
            tool_calls: vec![ToolCall::new("call_1", "search", Value::Null)],
        };
        let (next, actions) = transition(
            &RunState::CallingModel,
            RunInput::ModelCompleted {
                message: msg,
                usage: TokenUsage::new(100, 50),
            },
            &make_config(),
        );
        assert_eq!(next, RunState::ExecutingTools);
        assert!(matches!(
            actions.as_slice(),
            [RunAction::ExecuteTool { .. }]
        ));
    }

    #[test]
    fn calling_model_without_tools_finishes() {
        let msg = Message::assistant_text("done");
        let (next, actions) = transition(
            &RunState::CallingModel,
            RunInput::ModelCompleted {
                message: msg,
                usage: TokenUsage::new(100, 50),
            },
            &make_config(),
        );
        assert_eq!(next, RunState::Finished);
        assert!(matches!(actions.as_slice(), [RunAction::FinishRun { .. }]));
    }

    #[test]
    fn terminal_states_no_transition() {
        for state in &[RunState::Finished, RunState::Aborted] {
            let (next, actions) = transition(
                state,
                RunInput::UserMessageReceived {
                    content: vec![ContentPart::text("hello")],
                },
                &make_config(),
            );
            assert_eq!(next, *state);
            assert!(actions.is_empty());
        }
    }

    #[test]
    fn approval_granted_executes_tool() {
        let (next, actions) = transition(
            &RunState::WaitingApproval,
            RunInput::ToolApprovalGranted {
                call_id: "call_1".to_string(),
            },
            &make_config(),
        );
        assert_eq!(next, RunState::ExecutingTools);
        assert!(matches!(
            actions.as_slice(),
            [RunAction::ExecuteTool { .. }]
        ));
    }

    #[test]
    fn approval_rejected_goes_to_building_context() {
        let (next, _actions) = transition(
            &RunState::WaitingApproval,
            RunInput::ToolApprovalRejected {
                call_id: "call_1".to_string(),
                reason: Some("too dangerous".to_string()),
            },
            &make_config(),
        );
        assert_eq!(next, RunState::BuildingContext);
    }

    #[test]
    fn deterministic_same_input_same_output() {
        let state = RunState::Idle;
        let config = make_config();
        let input = RunInput::UserMessageReceived {
            content: vec![ContentPart::text("hello")],
        };

        let (next1, actions1) = transition(&state, input.clone(), &config);
        let (next2, actions2) = transition(&state, input, &config);

        assert_eq!(next1, next2);
        // Compare actions by debug representation
        assert_eq!(format!("{actions1:?}"), format!("{actions2:?}"));
    }

    #[test]
    fn streaming_chunks_keep_streaming_state() {
        let (next, actions) = transition(
            &RunState::StreamingModel,
            RunInput::ModelChunkReceived {
                delta: "hello".to_string(),
            },
            &make_config(),
        );
        assert_eq!(next, RunState::StreamingModel);
        assert!(matches!(actions.as_slice(), [RunAction::Noop]));
    }
}