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
//! Kernel actor implementation.
//!
//! The Kernel is the central coordinator and supervisor of the entire
//! Acton-AI system. It manages agent lifecycles, routes inter-agent
//! communication, and handles agent failures through supervision.

use crate::kernel::discovery::CapabilityRegistry;
use crate::kernel::logging::init_and_store_logging;
use crate::kernel::KernelConfig;
use crate::messages::{
    AgentMessage, AgentSpawned, AnnounceCapabilities, CapableAgentFound, DelegateTask,
    FindCapableAgent, GetAgentStatus, IncomingAgentMessage, IncomingTask, RouteMessage, SpawnAgent,
    StopAgent, SystemEvent,
};
use acton_reactive::prelude::*;
use std::collections::HashMap;

/// Metrics collected by the Kernel.
#[derive(Debug, Clone, Default)]
pub struct KernelMetrics {
    /// Total number of agents spawned
    pub agents_spawned: usize,
    /// Total number of agents stopped
    pub agents_stopped: usize,
    /// Total number of messages routed
    pub messages_routed: usize,
}

/// Message to initialize the kernel with configuration.
#[acton_message]
pub struct InitKernel {
    /// Kernel configuration
    pub config: KernelConfig,
}

/// The Kernel actor state.
///
/// The Kernel maintains a registry of all active agents and supervises
/// their lifecycles using the OneForOne supervision strategy.
#[acton_actor]
pub struct Kernel {
    /// Configuration for the kernel
    pub config: KernelConfig,
    /// Registry of active agents (AgentId -> ActorHandle)
    pub agents: HashMap<String, ActorHandle>,
    /// Metrics for monitoring
    pub metrics: KernelMetrics,
    /// Whether the kernel is shutting down
    pub shutting_down: bool,
    /// Registry of agent capabilities for discovery
    pub capability_registry: CapabilityRegistry,
}

impl Kernel {
    /// Spawns the Kernel actor with default configuration.
    ///
    /// This creates and starts the Kernel actor, which will supervise
    /// all agent actors in the system.
    ///
    /// # Arguments
    ///
    /// * `runtime` - The ActorRuntime
    ///
    /// # Returns
    ///
    /// The ActorHandle for the started Kernel actor.
    pub async fn spawn(runtime: &mut ActorRuntime) -> ActorHandle {
        Self::spawn_with_config(runtime, KernelConfig::default()).await
    }

    /// Spawns the Kernel actor with the given configuration.
    ///
    /// If logging is configured, this will automatically initialize file-based logging
    /// before starting the kernel. Logs are written to the configured directory
    /// (default: `~/.local/share/acton/logs/`).
    ///
    /// # Arguments
    ///
    /// * `runtime` - The ActorRuntime
    /// * `config` - Configuration for the kernel
    ///
    /// # Returns
    ///
    /// The ActorHandle for the started Kernel actor.
    pub async fn spawn_with_config(
        runtime: &mut ActorRuntime,
        config: KernelConfig,
    ) -> ActorHandle {
        // Initialize file logging before any tracing calls
        if let Some(ref logging_config) = config.logging {
            match init_and_store_logging(logging_config) {
                Ok(true) => {
                    // Logging initialized successfully - log to the file
                    if let Ok(log_dir) = crate::kernel::logging::get_log_dir(logging_config) {
                        tracing::info!(
                            log_dir = %log_dir.display(),
                            app_name = %logging_config.app_name,
                            "File logging initialized"
                        );
                    }
                }
                Ok(false) => {
                    // Logging disabled or already initialized - nothing to do
                }
                Err(e) => {
                    // Log to stderr since file logging failed
                    eprintln!("Warning: file logging initialization failed: {e}");
                }
            }
        }

        let mut builder = runtime.new_actor_with_name::<Kernel>("kernel".to_string());

        // Store config for use in init message
        let kernel_config = config.clone();

        // Set up lifecycle hooks (immutable, just for logging)
        builder
            .before_start(|_actor| {
                tracing::debug!("Kernel initializing");
                Reply::ready()
            })
            .after_start(|actor| {
                tracing::info!(
                    max_agents = actor.model.config.max_agents,
                    "Kernel ready to accept agent spawn requests"
                );
                Reply::ready()
            })
            .before_stop(|actor| {
                tracing::info!(
                    active_agents = actor.model.agents.len(),
                    total_spawned = actor.model.metrics.agents_spawned,
                    "Kernel shutting down"
                );
                Reply::ready()
            });

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

        let handle = builder.start().await;

        // Initialize kernel with config
        handle
            .send(InitKernel {
                config: kernel_config,
            })
            .await;

        handle
    }
}

/// Configures message handlers for the Kernel actor.
fn configure_handlers(builder: &mut ManagedActor<Idle, Kernel>) {
    // Handle kernel initialization
    builder.mutate_on::<InitKernel>(|actor, envelope| {
        actor.model.config = envelope.message().config.clone();
        actor.model.shutting_down = false;

        tracing::info!(
            max_agents = actor.model.config.max_agents,
            metrics_enabled = actor.model.config.enable_metrics,
            "Kernel configured"
        );

        Reply::ready()
    });

    // Handle SpawnAgent requests
    builder.mutate_on::<SpawnAgent>(|actor, envelope| {
        let config = envelope.message().config.clone();
        let reply = envelope.reply_envelope();

        // Check if we're shutting down
        if actor.model.shutting_down {
            tracing::warn!("Rejecting spawn request - kernel is shutting down");
            return Reply::ready();
        }

        // Check agent limit
        if actor.model.agents.len() >= actor.model.config.max_agents {
            tracing::warn!(
                current = actor.model.agents.len(),
                max = actor.model.config.max_agents,
                "Rejecting spawn request - agent limit reached"
            );
            return Reply::ready();
        }

        let agent_id = config.agent_id();
        tracing::info!(
            agent_id = %agent_id,
            name = ?config.name,
            "Spawning new agent"
        );

        // Store the agent ID for later use
        let spawned_id = agent_id.clone();

        // Update metrics
        actor.model.metrics.agents_spawned += 1;

        // Broadcast agent spawned event
        let broker = actor.broker().clone();

        Reply::pending(async move {
            broker
                .broadcast(SystemEvent::AgentSpawned {
                    id: spawned_id.clone(),
                })
                .await;

            reply
                .send(AgentSpawned {
                    agent_id: spawned_id,
                })
                .await;
        })
    });

    // Handle StopAgent requests
    builder.mutate_on::<StopAgent>(|actor, envelope| {
        let agent_id = &envelope.message().agent_id;
        let agent_id_str = agent_id.to_string();

        if let Some(handle) = actor.model.agents.remove(&agent_id_str) {
            tracing::info!(agent_id = %agent_id, "Stopping agent");

            actor.model.metrics.agents_stopped += 1;

            // Broadcast agent stopped event
            let broker = actor.broker().clone();
            let stopped_id = agent_id.clone();

            Reply::pending(async move {
                broker
                    .broadcast(SystemEvent::AgentStopped {
                        id: stopped_id,
                        reason: "requested".to_string(),
                    })
                    .await;

                // Send stop signal to the agent
                let _ = handle.stop().await;
            })
        } else {
            tracing::warn!(agent_id = %agent_id, "Agent not found for stop request");
            Reply::ready()
        }
    });

    // Handle RouteMessage - forward messages between agents
    builder.mutate_on::<RouteMessage>(|actor, envelope| {
        let msg = envelope.message();
        let to_str = msg.to.to_string();

        if let Some(target_handle) = actor.model.agents.get(&to_str) {
            tracing::debug!(
                from = %msg.from,
                to = %msg.to,
                payload_length = msg.payload.len(),
                "Routing message between agents"
            );

            actor.model.metrics.messages_routed += 1;

            let handle = target_handle.clone();
            let payload = msg.payload.clone();
            let from = msg.from.clone();

            Reply::pending(async move {
                // Log the routed message for debugging
                tracing::debug!(
                    from = %from,
                    payload = %payload,
                    "Message routed to agent"
                );
                drop(handle);
            })
        } else {
            tracing::warn!(
                from = %msg.from,
                to = %msg.to,
                "Cannot route message - target agent not found"
            );
            Reply::ready()
        }
    });

    // Handle GetAgentStatus requests
    builder.act_on::<GetAgentStatus>(|actor, envelope| {
        let agent_id = &envelope.message().agent_id;
        let agent_id_str = agent_id.to_string();

        if let Some(agent_handle) = actor.model.agents.get(&agent_id_str) {
            let handle = agent_handle.clone();
            let id = agent_id.clone();

            Reply::pending(async move {
                // Forward the status request to the agent
                handle.send(GetAgentStatus { agent_id: id }).await;
            })
        } else {
            tracing::warn!(agent_id = %agent_id, "Agent not found for status request");
            Reply::ready()
        }
    });

    // Handle ChildTerminated events for supervised agents
    builder.mutate_on::<ChildTerminated>(|_actor, envelope| {
        let msg = envelope.message();
        tracing::info!(
            child_id = ?msg.child_id,
            reason = ?msg.reason,
            "Child actor terminated"
        );

        // Find and remove the terminated agent
        // Supervision strategy can be configured per-agent in future releases

        Reply::ready()
    });

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

    // Handle AgentMessage - route to target agent
    builder.try_mutate_on::<AgentMessage, (), crate::error::MultiAgentError>(|actor, envelope| {
        let msg = envelope.message();
        let to_str = msg.to.to_string();

        // Check if target agent exists
        if let Some(target_handle) = actor.model.agents.get(&to_str) {
            let handle = target_handle.clone();
            let incoming = IncomingAgentMessage::from(msg.clone());

            tracing::debug!(
                from = %msg.from,
                to = %msg.to,
                "Routing agent message"
            );

            actor.model.metrics.messages_routed += 1;

            Reply::try_pending(async move {
                handle.send(incoming).await;
                Ok(())
            })
        } else {
            tracing::warn!(to = %msg.to, "Target agent not found for message");
            Reply::try_err(crate::error::MultiAgentError::agent_not_found(
                msg.to.clone(),
            ))
        }
    });

    // Handle DelegateTask - route to target agent
    builder.try_mutate_on::<DelegateTask, (), crate::error::MultiAgentError>(|actor, envelope| {
        let msg = envelope.message();
        let to_str = msg.to.to_string();

        if let Some(target_handle) = actor.model.agents.get(&to_str) {
            let handle = target_handle.clone();
            let incoming = IncomingTask::from_delegate(msg);

            tracing::info!(
                from = %msg.from,
                to = %msg.to,
                task_id = %msg.task_id,
                task_type = %msg.task_type,
                "Routing task delegation"
            );

            actor.model.metrics.messages_routed += 1;

            Reply::try_pending(async move {
                handle.send(incoming).await;
                Ok(())
            })
        } else {
            tracing::warn!(to = %msg.to, "Target agent not found for task delegation");
            Reply::try_err(crate::error::MultiAgentError::agent_not_found(
                msg.to.clone(),
            ))
        }
    });

    // Handle AnnounceCapabilities - update capability registry
    builder.mutate_on::<AnnounceCapabilities>(|actor, envelope| {
        let msg = envelope.message();

        actor
            .model
            .capability_registry
            .register(msg.agent_id.clone(), msg.capabilities.clone());

        tracing::info!(
            agent_id = %msg.agent_id,
            capabilities = ?msg.capabilities,
            "Agent capabilities registered"
        );

        Reply::ready()
    });

    // Handle FindCapableAgent - search capability registry
    builder.act_on::<FindCapableAgent>(|actor, envelope| {
        let msg = envelope.message();
        let reply = envelope.reply_envelope();

        let agent_id = actor
            .model
            .capability_registry
            .find_capable_agent(&msg.capability);

        tracing::debug!(
            capability = %msg.capability,
            found = agent_id.is_some(),
            "Capability search"
        );

        let response = CapableAgentFound {
            correlation_id: msg.correlation_id.clone(),
            agent_id,
            capability: msg.capability.clone(),
        };

        Reply::pending(async move {
            reply.send(response).await;
        })
    });
}

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

    #[test]
    fn kernel_metrics_default() {
        let metrics = KernelMetrics::default();
        assert_eq!(metrics.agents_spawned, 0);
        assert_eq!(metrics.agents_stopped, 0);
        assert_eq!(metrics.messages_routed, 0);
    }
}