acton-ai 0.26.0

An agentic AI framework where each agent is an actor
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
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
//! Agent actor implementation.
//!
//! The Agent actor represents an individual AI agent with its own state,
//! conversation history, and reasoning loop.

use crate::agent::delegation::DelegationTracker;
use crate::agent::{AgentConfig, AgentState};
use crate::llm::StreamAccumulator;
use crate::messages::{
    AgentStatusResponse, GetAgentStatus, GetStatus, IncomingAgentMessage, IncomingTask, LLMRequest,
    LLMResponse, LLMStreamEnd, LLMStreamStart, LLMStreamToken, LLMStreamToolCall, Message,
    StopReason, TaskAccepted, TaskCompleted, TaskFailed, ToolDefinition, UserPrompt,
};
use crate::tools::actor::{ExecuteToolDirect, ToolActorResponse};
use crate::types::{AgentId, CorrelationId};
use acton_reactive::prelude::*;
use std::collections::HashMap;

/// Internal state for a pending LLM request.
#[derive(Debug, Clone, Default)]
pub struct PendingLLMRequest {
    /// The correlation ID for this request
    pub correlation_id: Option<CorrelationId>,
    /// The original user prompt that triggered this request
    pub original_prompt: String,
}

/// Message to initialize agent with configuration.
#[acton_message]
pub struct InitAgent {
    /// The agent configuration
    pub config: AgentConfig,
}

/// Message to register tool actors with an agent.
///
/// This should be sent after the agent is initialized but before prompts are sent.
/// The caller is responsible for spawning the tool actors.
#[acton_message]
pub struct RegisterToolActors {
    /// Tool actors to register: (name, handle, definition)
    pub tools: Vec<(String, ActorHandle, ToolDefinition)>,
}

/// The Agent actor state.
///
/// Each agent maintains its own conversation history, state, and pending requests.
#[acton_actor]
pub struct Agent {
    /// Unique identifier for this agent
    pub id: Option<AgentId>,
    /// The system prompt defining agent behavior
    pub system_prompt: String,
    /// Optional display name
    pub name: Option<String>,
    /// Conversation history
    pub conversation: Vec<Message>,
    /// Current state in the reasoning loop
    pub state: AgentState,
    /// Maximum conversation history length
    pub max_conversation_length: usize,
    /// Whether streaming is enabled
    pub enable_streaming: bool,
    /// Pending LLM requests awaiting response
    pub pending_llm: HashMap<String, PendingLLMRequest>,
    /// Pending tool calls awaiting response
    pub pending_tools: HashMap<String, String>,
    /// Stream accumulator for receiving streamed responses
    pub stream_accumulator: StreamAccumulator,
    /// Tracker for delegated tasks (both outgoing and incoming)
    pub delegation_tracker: DelegationTracker,
    /// Handles to tool actors owned by this agent
    pub tool_handles: HashMap<String, ActorHandle>,
    /// Tool definitions for tools available to this agent
    pub tool_definitions: Vec<ToolDefinition>,
}

impl Agent {
    /// Creates a new Agent actor builder with the given runtime.
    ///
    /// This sets up the actor state and configures all message handlers.
    /// The actor is not started until `start()` is called on the returned builder.
    /// After starting, send an `InitAgent` message to configure the agent.
    ///
    /// # Arguments
    ///
    /// * `runtime` - The Acton runtime to create the actor in
    ///
    /// # Returns
    ///
    /// A `ManagedActor<Idle, Agent>` that can be further configured and started.
    pub fn create(runtime: &mut ActorRuntime) -> ManagedActor<Idle, Agent> {
        let mut builder = runtime.new_actor::<Agent>();

        // Set up lifecycle hooks (immutable, just for logging)
        builder
            .before_start(|_actor| {
                tracing::debug!("Agent initializing");
                Reply::ready()
            })
            .after_start(|actor| {
                tracing::info!(
                    agent_id = ?actor.model.id,
                    "Agent ready for messages"
                );
                Reply::ready()
            })
            .before_stop(|actor| {
                tracing::info!(
                    agent_id = ?actor.model.id,
                    conversation_length = actor.model.conversation.len(),
                    "Agent stopping"
                );
                Reply::ready()
            });

        // Configure message handlers
        configure_handlers(&mut builder);

        builder
    }

    /// Adds a message to the conversation history, respecting max length.
    pub fn add_message(&mut self, message: Message) {
        self.conversation.push(message);

        // Trim conversation if it exceeds max length
        // Keep system messages and recent messages
        if self.conversation.len() > self.max_conversation_length {
            let excess = self.conversation.len() - self.max_conversation_length;
            // Remove from the beginning, but keep index 0 if it's a system message
            let start_index = if self
                .conversation
                .first()
                .map(|m| m.role == crate::messages::MessageRole::System)
                .unwrap_or(false)
            {
                1
            } else {
                0
            };
            self.conversation.drain(start_index..start_index + excess);
        }
    }

    /// Clears the conversation history.
    pub fn clear_conversation(&mut self) {
        self.conversation.clear();
    }

    /// Returns the current conversation length.
    #[must_use]
    pub fn conversation_length(&self) -> usize {
        self.conversation.len()
    }
}

/// Configures message handlers for the Agent actor.
fn configure_handlers(builder: &mut ManagedActor<Idle, Agent>) {
    // Handle initialization message
    builder.mutate_on::<InitAgent>(|actor, envelope| {
        let config = &envelope.message().config;

        actor.model.id = Some(config.agent_id());
        actor.model.system_prompt = config.system_prompt.clone();
        actor.model.name = config.name.clone();
        actor.model.max_conversation_length = config.max_conversation_length;
        actor.model.enable_streaming = config.enable_streaming;
        actor.model.state = AgentState::Idle;

        tracing::info!(
            agent_id = ?actor.model.id,
            name = ?actor.model.name,
            "Agent configured"
        );

        Reply::ready()
    });

    // Handle user prompts - starts the reasoning loop
    builder.mutate_on::<UserPrompt>(|actor, envelope| {
        let prompt = envelope.message();

        // Check if we can accept a new prompt
        if !actor.model.state.can_accept_prompt() {
            tracing::warn!(
                agent_id = ?actor.model.id,
                current_state = %actor.model.state,
                "Rejecting prompt - agent is busy"
            );
            return Reply::ready();
        }

        tracing::info!(
            agent_id = ?actor.model.id,
            correlation_id = %prompt.correlation_id,
            content_length = prompt.content.len(),
            "Received user prompt"
        );

        // Transition to Thinking state
        actor.model.state = AgentState::Thinking;

        // Add user message to conversation
        actor.model.add_message(Message::user(&prompt.content));

        // Store pending request
        let corr_id_str = prompt.correlation_id.to_string();
        actor.model.pending_llm.insert(
            corr_id_str.clone(),
            PendingLLMRequest {
                correlation_id: Some(prompt.correlation_id.clone()),
                original_prompt: prompt.content.clone(),
            },
        );

        // Build conversation messages including system prompt
        let mut messages = Vec::new();
        if !actor.model.system_prompt.is_empty() {
            messages.push(Message::system(&actor.model.system_prompt));
        }
        messages.extend(actor.model.conversation.clone());

        // Create LLM request with tools if available
        let llm_request = LLMRequest {
            correlation_id: prompt.correlation_id.clone(),
            agent_id: actor.model.id.clone().unwrap_or_default(),
            messages,
            tools: if actor.model.tool_definitions.is_empty() {
                None
            } else {
                Some(actor.model.tool_definitions.clone())
            },
            sampling: None,
        };

        // Broadcast LLM request via broker for LLM Provider to pick up
        let broker = actor.broker().clone();

        Reply::pending(async move {
            broker.broadcast(llm_request).await;
        })
    });

    // Handle LLM stream start
    builder.mutate_on::<LLMStreamStart>(|actor, envelope| {
        let msg = envelope.message();
        let corr_id_str = msg.correlation_id.to_string();

        // Check if this stream is for us
        if !actor.model.pending_llm.contains_key(&corr_id_str) {
            return Reply::ready();
        }

        tracing::debug!(
            agent_id = ?actor.model.id,
            correlation_id = %msg.correlation_id,
            "LLM stream started"
        );

        // Start accumulating the stream
        actor
            .model
            .stream_accumulator
            .start_stream(&msg.correlation_id);

        Reply::ready()
    });

    // Handle LLM stream tokens
    builder.mutate_on::<LLMStreamToken>(|actor, envelope| {
        let msg = envelope.message();
        let corr_id_str = msg.correlation_id.to_string();

        // Check if this token is for us
        if !actor.model.pending_llm.contains_key(&corr_id_str) {
            return Reply::ready();
        }

        // Append token to accumulator
        actor
            .model
            .stream_accumulator
            .append_token(&msg.correlation_id, &msg.token);

        tracing::trace!(
            agent_id = ?actor.model.id,
            correlation_id = %msg.correlation_id,
            token_len = msg.token.len(),
            "Received stream token"
        );

        Reply::ready()
    });

    // Handle LLM stream tool calls with fallible handler pattern
    builder
        .try_mutate_on::<LLMStreamToolCall, (), crate::error::AgentError>(|actor, envelope| {
            let msg = envelope.message();
            let corr_id_str = msg.correlation_id.to_string();

            // Check if this tool call is for us
            if !actor.model.pending_llm.contains_key(&corr_id_str) {
                return Reply::try_ok(());
            }

            // Validate tool call has required fields
            if msg.tool_call.name.is_empty() {
                return Reply::try_err(crate::error::AgentError::processing_failed(
                    actor.model.id.clone(),
                    "Tool call missing name",
                ));
            }

            if msg.tool_call.id.is_empty() {
                return Reply::try_err(crate::error::AgentError::processing_failed(
                    actor.model.id.clone(),
                    "Tool call missing ID",
                ));
            }

            tracing::debug!(
                agent_id = ?actor.model.id,
                correlation_id = %msg.correlation_id,
                tool_name = %msg.tool_call.name,
                "Received tool call"
            );

            // Add tool call to accumulator
            actor
                .model
                .stream_accumulator
                .add_tool_call(&msg.correlation_id, msg.tool_call.clone());

            Reply::try_ok(())
        })
        .on_error::<LLMStreamToolCall, crate::error::AgentError>(|actor, envelope, error| {
            tracing::error!(
                agent_id = ?actor.model.id,
                correlation_id = %envelope.message().correlation_id,
                error = %error,
                "Tool call processing failed"
            );
            Box::pin(async {})
        });

    // Handle LLM stream end with fallible handler pattern
    builder
        .try_mutate_on::<LLMStreamEnd, (), crate::error::AgentError>(|actor, envelope| {
            let msg = envelope.message();
            let corr_id_str = msg.correlation_id.to_string();

            // Check if this stream end is for us
            if !actor.model.pending_llm.contains_key(&corr_id_str) {
                return Reply::try_ok(());
            }

            tracing::debug!(
                agent_id = ?actor.model.id,
                correlation_id = %msg.correlation_id,
                stop_reason = ?msg.stop_reason,
                "LLM stream ended"
            );

            // Complete the stream and get accumulated content
            let stream = actor
                .model
                .stream_accumulator
                .end_stream(&msg.correlation_id, msg.stop_reason);

            let Some(stream) = stream else {
                // Stream was never started or already ended - this is an error
                return Reply::try_err(crate::error::AgentError::processing_failed(
                    actor.model.id.clone(),
                    format!("No active stream for correlation_id {}", msg.correlation_id),
                ));
            };

            // Add assistant response to conversation
            if stream.has_tool_calls() {
                actor.model.add_message(Message::assistant_with_tools(
                    stream.content.clone(),
                    stream.tool_calls.clone(),
                ));
                // Transition to Executing state for tool calls
                actor.model.state = AgentState::Executing;

                // Execute tool calls
                let tool_calls = stream.tool_calls.clone();
                let tool_handles = actor.model.tool_handles.clone();
                let corr_id = msg.correlation_id.clone();
                let corr_id_str = corr_id.to_string();

                // Track pending tool calls
                for tc in &tool_calls {
                    actor
                        .model
                        .pending_tools
                        .insert(tc.id.clone(), corr_id_str.clone());
                }

                // Don't remove from pending_llm yet - we'll need to continue the loop
                // Actually, we already removed it above. Let's re-add it for the loop.
                actor.model.pending_llm.insert(
                    corr_id_str.clone(),
                    PendingLLMRequest {
                        correlation_id: Some(corr_id.clone()),
                        original_prompt: String::new(),
                    },
                );

                // Execute each tool call
                return Reply::try_pending(async move {
                    for tc in tool_calls {
                        if let Some(handle) = tool_handles.get(&tc.name) {
                            let exec_msg = ExecuteToolDirect::new(
                                corr_id.clone(),
                                tc.id.clone(),
                                tc.arguments.clone(),
                            );
                            handle.send(exec_msg).await;
                        } else {
                            tracing::warn!(
                                tool_name = %tc.name,
                                tool_call_id = %tc.id,
                                "Tool not found for execution"
                            );
                        }
                    }
                    Ok::<(), crate::error::AgentError>(())
                });
            } else {
                actor
                    .model
                    .add_message(Message::assistant(stream.content.clone()));
                // Return to Idle state (or Completed based on stop reason)
                actor.model.state = match msg.stop_reason {
                    StopReason::MaxTokens => AgentState::Completed,
                    _ => AgentState::Idle,
                };
            }

            tracing::info!(
                agent_id = ?actor.model.id,
                correlation_id = %msg.correlation_id,
                content_len = stream.content.len(),
                tool_calls = stream.tool_calls.len(),
                "Completed LLM response"
            );

            // Remove from pending
            actor.model.pending_llm.remove(&corr_id_str);

            Reply::try_ok(())
        })
        .on_error::<LLMStreamEnd, crate::error::AgentError>(|actor, envelope, error| {
            let corr_id_str = envelope.message().correlation_id.to_string();

            tracing::error!(
                agent_id = ?actor.model.id,
                correlation_id = %envelope.message().correlation_id,
                error = %error,
                "Stream finalization failed"
            );

            // Clean up the pending request on error
            actor.model.pending_llm.remove(&corr_id_str);

            // Reset state to Idle on error
            actor.model.state = AgentState::Idle;

            Box::pin(async {})
        });

    // Handle complete LLM responses (non-streaming fallback)
    builder.mutate_on::<LLMResponse>(|actor, envelope| {
        let msg = envelope.message();
        let corr_id_str = msg.correlation_id.to_string();

        // Check if this response is for us
        if !actor.model.pending_llm.contains_key(&corr_id_str) {
            return Reply::ready();
        }

        // If we already processed via streaming, skip the complete response
        if actor
            .model
            .stream_accumulator
            .get_stream(&msg.correlation_id)
            .is_some()
        {
            return Reply::ready();
        }

        tracing::debug!(
            agent_id = ?actor.model.id,
            correlation_id = %msg.correlation_id,
            content_len = msg.content.len(),
            "Received complete LLM response"
        );

        // Add assistant response to conversation
        if let Some(tool_calls) = &msg.tool_calls {
            actor.model.add_message(Message::assistant_with_tools(
                msg.content.clone(),
                tool_calls.clone(),
            ));
            actor.model.state = AgentState::Executing;
        } else {
            actor
                .model
                .add_message(Message::assistant(msg.content.clone()));
            actor.model.state = match msg.stop_reason {
                StopReason::MaxTokens => AgentState::Completed,
                _ => AgentState::Idle,
            };
        }

        // Remove from pending
        actor.model.pending_llm.remove(&corr_id_str);

        Reply::ready()
    });

    // Handle status requests (read-only)
    builder.act_on::<GetStatus>(|actor, envelope| {
        let reply = envelope.reply_envelope();
        let agent_id = actor.model.id.clone().unwrap_or_else(AgentId::new);
        let state = actor.model.state.to_string();
        let conversation_length = actor.model.conversation_length();

        Reply::pending(async move {
            reply
                .send(AgentStatusResponse {
                    agent_id,
                    state,
                    conversation_length,
                })
                .await;
        })
    });

    // Handle status requests from kernel
    builder.act_on::<GetAgentStatus>(|actor, envelope| {
        let reply = envelope.reply_envelope();
        let agent_id = actor.model.id.clone().unwrap_or_else(AgentId::new);
        let state = actor.model.state.to_string();
        let conversation_length = actor.model.conversation_length();

        Reply::pending(async move {
            reply
                .send(AgentStatusResponse {
                    agent_id,
                    state,
                    conversation_length,
                })
                .await;
        })
    });

    // =========================================================================
    // Multi-Agent Message Handlers (Phase 6)
    // =========================================================================

    // Handle incoming messages from other agents
    builder.mutate_on::<IncomingAgentMessage>(|actor, envelope| {
        let msg = envelope.message();

        tracing::info!(
            agent_id = ?actor.model.id,
            from = %msg.from,
            content_len = msg.content.len(),
            "Received message from another agent"
        );

        // Add to conversation as a user message (from another agent)
        let content = format!("[From Agent {}]: {}", msg.from, msg.content);
        actor.model.add_message(Message::user(content));

        Reply::ready()
    });

    // Handle incoming task delegations
    builder.mutate_on::<IncomingTask>(|actor, envelope| {
        let msg = envelope.message();

        tracing::info!(
            agent_id = ?actor.model.id,
            from = %msg.from,
            task_id = %msg.task_id,
            task_type = %msg.task_type,
            "Received delegated task"
        );

        // Track the incoming task
        actor.model.delegation_tracker.track_incoming(
            msg.task_id.clone(),
            msg.from.clone(),
            msg.task_type.clone(),
        );

        // Auto-accept the task and broadcast TaskAccepted
        actor.model.delegation_tracker.accept_incoming(&msg.task_id);

        let broker = actor.broker().clone();
        let agent_id = actor.model.id.clone().unwrap_or_default();
        let task_id = msg.task_id.clone();

        Reply::pending(async move {
            broker.broadcast(TaskAccepted { task_id, agent_id }).await;
        })
    });

    // Handle task acceptance notifications
    builder.mutate_on::<TaskAccepted>(|actor, envelope| {
        let msg = envelope.message();

        if let Some(task) = actor
            .model
            .delegation_tracker
            .get_outgoing_mut(&msg.task_id)
        {
            task.accept();
            tracing::debug!(
                task_id = %msg.task_id,
                agent_id = %msg.agent_id,
                "Delegated task accepted"
            );
        }

        Reply::ready()
    });

    // Handle task completion notifications
    builder.mutate_on::<TaskCompleted>(|actor, envelope| {
        let msg = envelope.message();

        if let Some(task) = actor
            .model
            .delegation_tracker
            .get_outgoing_mut(&msg.task_id)
        {
            task.complete(msg.result.clone());
            tracing::info!(
                task_id = %msg.task_id,
                "Delegated task completed"
            );
        }

        Reply::ready()
    });

    // Handle task failure notifications
    builder.mutate_on::<TaskFailed>(|actor, envelope| {
        let msg = envelope.message();

        if let Some(task) = actor
            .model
            .delegation_tracker
            .get_outgoing_mut(&msg.task_id)
        {
            task.fail(&msg.error);
            tracing::warn!(
                task_id = %msg.task_id,
                error = %msg.error,
                "Delegated task failed"
            );
        }

        Reply::ready()
    });

    // =========================================================================
    // Per-Agent Tool Handlers
    // =========================================================================

    // Handle registration of tool actors
    builder.mutate_on::<RegisterToolActors>(|actor, envelope| {
        let msg = envelope.message();

        for (name, handle, definition) in &msg.tools {
            actor
                .model
                .tool_handles
                .insert(name.clone(), handle.clone());
            actor.model.tool_definitions.push(definition.clone());

            tracing::debug!(
                agent_id = ?actor.model.id,
                tool_name = %name,
                "Tool actor registered"
            );
        }

        tracing::info!(
            agent_id = ?actor.model.id,
            tool_count = msg.tools.len(),
            "Tool actors registered"
        );

        Reply::ready()
    });

    // Handle tool execution responses
    builder.mutate_on::<ToolActorResponse>(|actor, envelope| {
        let msg = envelope.message();
        let tool_call_id = &msg.tool_call_id;

        // Check if this response is for a pending tool call
        if !actor.model.pending_tools.contains_key(tool_call_id) {
            return Reply::ready();
        }

        let corr_id_str = actor.model.pending_tools.remove(tool_call_id);

        match &msg.result {
            Ok(content) => {
                tracing::debug!(
                    agent_id = ?actor.model.id,
                    tool_call_id = %tool_call_id,
                    content_len = content.len(),
                    "Tool execution succeeded"
                );

                // Add tool result to conversation
                actor
                    .model
                    .add_message(Message::tool(tool_call_id.clone(), content.clone()));
            }
            Err(error) => {
                tracing::warn!(
                    agent_id = ?actor.model.id,
                    tool_call_id = %tool_call_id,
                    error = %error,
                    "Tool execution failed"
                );

                // Add error result to conversation
                actor.model.add_message(Message::tool(
                    tool_call_id.clone(),
                    format!("Error: {error}"),
                ));
            }
        }

        // If no more pending tool calls, transition back to Thinking
        // to continue the reasoning loop
        if actor.model.pending_tools.is_empty() && actor.model.state == AgentState::Executing {
            actor.model.state = AgentState::Thinking;

            // Build conversation messages including system prompt and tools
            let mut messages = Vec::new();
            if !actor.model.system_prompt.is_empty() {
                messages.push(Message::system(&actor.model.system_prompt));
            }
            messages.extend(actor.model.conversation.clone());

            // Create LLM request to continue reasoning
            if let Some(corr_id_str) = corr_id_str {
                if let Ok(correlation_id) = corr_id_str.parse::<CorrelationId>() {
                    let llm_request = LLMRequest {
                        correlation_id: correlation_id.clone(),
                        agent_id: actor.model.id.clone().unwrap_or_default(),
                        messages,
                        tools: if actor.model.tool_definitions.is_empty() {
                            None
                        } else {
                            Some(actor.model.tool_definitions.clone())
                        },
                        sampling: None,
                    };

                    // Re-add to pending
                    actor.model.pending_llm.insert(
                        corr_id_str,
                        PendingLLMRequest {
                            correlation_id: Some(correlation_id),
                            original_prompt: String::new(),
                        },
                    );

                    let broker = actor.broker().clone();
                    return Reply::pending(async move {
                        broker.broadcast(llm_request).await;
                    });
                }
            }
        }

        Reply::ready()
    });
}

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

    #[test]
    fn add_message_respects_max_length() {
        let mut agent = Agent::default();
        agent.max_conversation_length = 5;

        for i in 0..10 {
            agent.add_message(Message::user(format!("Message {}", i)));
        }

        assert_eq!(agent.conversation.len(), 5);
    }

    #[test]
    fn add_message_preserves_system_message() {
        let mut agent = Agent::default();
        agent.max_conversation_length = 3;

        // Add system message first
        agent.add_message(Message::system("You are helpful"));

        // Add more messages than max
        for i in 0..5 {
            agent.add_message(Message::user(format!("Message {}", i)));
        }

        // System message should still be at index 0
        assert_eq!(agent.conversation.len(), 3);
        assert_eq!(
            agent.conversation[0].role,
            crate::messages::MessageRole::System
        );
    }

    #[test]
    fn clear_conversation_empties_history() {
        let mut agent = Agent::default();
        agent.max_conversation_length = 10;
        agent.add_message(Message::user("Hello"));
        agent.add_message(Message::assistant("Hi"));

        assert_eq!(agent.conversation_length(), 2);

        agent.clear_conversation();

        assert_eq!(agent.conversation_length(), 0);
    }
}