modular-agent-core 0.25.0

Modular Agent Core
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
use std::any::Any;
use std::sync::Arc;

use async_trait::async_trait;
use serde_json::Value;

use crate::config::AgentConfigs;
use crate::context::AgentContext;
use crate::error::AgentError;
use crate::modular_agent::ModularAgent;
use crate::runtime::runtime;
use crate::spec::AgentSpec;
use crate::value::AgentValue;

/// The lifecycle status of an agent.
#[derive(Debug, Default, Clone, PartialEq)]
pub enum AgentStatus {
    #[default]
    Init,
    Start,
    Stop,
}

/// Internal messages sent to agents.
pub(crate) enum AgentMessage {
    /// Input value received on a port.
    Input {
        ctx: AgentContext,
        port: String,
        value: AgentValue,
    },

    /// Configuration value update.
    Config { key: String, value: AgentValue },

    /// Full configuration update.
    Configs { configs: AgentConfigs },

    /// Stop the agent.
    Stop,
}

/// The core trait for all agents.
///
/// All agents implement this trait. Defines lifecycle management,
/// configuration access, and message processing.
#[async_trait]
pub trait Agent: Send + Sync + 'static {
    /// Constructs a new agent instance.
    fn new(ma: ModularAgent, id: String, spec: AgentSpec) -> Result<Self, AgentError>
    where
        Self: Sized;

    /// Returns the `ModularAgent`.
    fn ma(&self) -> &ModularAgent;

    /// Returns the unique agent ID.
    fn id(&self) -> &str;

    /// Returns the current lifecycle status.
    fn status(&self) -> &AgentStatus;

    /// Returns the agent specification.
    fn spec(&self) -> &AgentSpec;

    /// Updates the agent specification.
    fn update_spec(&mut self, spec_update: &Value) -> Result<(), AgentError>;

    /// Returns the agent definition name.
    fn def_name(&self) -> &str;

    /// Returns the agent's configuration.
    ///
    /// # Errors
    ///
    /// Returns `NoConfig` if no configuration is available.
    fn configs(&self) -> Result<&AgentConfigs, AgentError>;

    /// Sets a configuration value.
    fn set_config(&mut self, key: String, value: AgentValue) -> Result<(), AgentError>;

    /// Sets the entire configuration.
    fn set_configs(&mut self, configs: AgentConfigs) -> Result<(), AgentError>;

    /// Gets global configuration for this agent.
    fn get_global_configs(&self) -> Option<AgentConfigs> {
        self.ma().get_global_configs(self.def_name())
    }

    /// Returns the preset ID this agent belongs to.
    fn preset_id(&self) -> &str;

    /// Sets the preset ID.
    fn set_preset_id(&mut self, preset_id: String);

    /// Starts the agent.
    ///
    /// Called when the workflow starts. Use for initialization and initial output.
    async fn start(&mut self) -> Result<(), AgentError>;

    /// Stops the agent.
    async fn stop(&mut self) -> Result<(), AgentError>;

    /// Processes an input message.
    ///
    /// Called when the agent receives a value on an input port.
    async fn process(
        &mut self,
        ctx: AgentContext,
        port: String,
        value: AgentValue,
    ) -> Result<(), AgentError>;

    /// Returns the tokio runtime.
    fn runtime(&self) -> &tokio::runtime::Runtime {
        runtime()
    }

    fn as_any(&self) -> &dyn Any;

    fn as_any_mut(&mut self) -> &mut dyn Any;
}

impl dyn Agent {
    pub fn as_agent<T: Agent>(&self) -> Option<&T> {
        self.as_any().downcast_ref::<T>()
    }

    pub fn as_agent_mut<T: Agent>(&mut self) -> Option<&mut T> {
        self.as_any_mut().downcast_mut::<T>()
    }
}

/// Core data structure for an agent.
///
/// Used by agents implementing `AsAgent` to store common state.
/// The `#[modular_agent]` macro generates a struct with this as a field.
pub struct AgentData {
    /// The ModularAgent instance.
    pub ma: ModularAgent,

    /// The unique identifier for this agent.
    pub id: String,

    /// The specification of the agent (definition, config, etc.).
    pub spec: AgentSpec,

    /// The preset identifier for the agent.
    /// Empty string when the agent does not belong to any preset.
    pub preset_id: String,

    /// The current lifecycle status of the agent.
    pub status: AgentStatus,
}

impl AgentData {
    /// Creates a new `AgentData` instance.
    ///
    /// Removes any `_`-prefixed config keys that were preserved by
    /// `AgentDefinition::reconcile_spec()` for lazy migration.
    /// Agents can read these keys from the `spec` parameter in `AsAgent::new()`
    /// before calling this method.
    pub fn new(ma: ModularAgent, id: String, mut spec: AgentSpec) -> Self {
        if let Some(ref mut configs) = spec.configs {
            configs.retain(|key, _| !key.starts_with('_'));
        }
        Self {
            ma,
            id,
            spec,
            preset_id: String::new(),
            status: AgentStatus::Init,
        }
    }
}

/// Trait for types that contain `AgentData`.
///
/// Required by `AsAgent`. Usually implemented automatically via `#[modular_agent]` macro.
pub trait HasAgentData {
    fn data(&self) -> &AgentData;

    fn mut_data(&mut self) -> &mut AgentData;
}

/// Simplified trait for implementing custom agents.
///
/// Implement this trait instead of `Agent` directly.
/// The `Agent` trait is automatically implemented for all types that implement `AsAgent`.
///
/// # Cancellation safety
///
/// The agent loop races [`process()`](Self::process) against the agent's
/// cancellation token, which fires when the agent (or its whole preset) is
/// stopped. On cancellation the in-flight `process()` future is **dropped at
/// whatever await point it has reached** — implementations must not rely on
/// running to completion. In particular, outputs emitted before the drop
/// stay emitted, and internal bookkeeping updated across await points (e.g.
/// entries in a pending map) may be left behind; keep such state consistent
/// at every await point or clean it up in [`stop()`](Self::stop).
///
/// Flow-level aborts ([`ModularAgent::abort_context`](crate::ModularAgent::abort_context))
/// are cooperative: the context's token fires, but messages carrying it are
/// still delivered so that wind-down outputs (e.g. an aborted final message
/// replacing a dangling partial in history) can traverse the graph.
/// Implementations that initiate external work (network requests, DB writes,
/// message posts) must therefore check
/// [`ctx.is_cancelled()`](crate::AgentContext::is_cancelled) before starting
/// it, and may select on
/// [`ctx.cancel_token()`](crate::AgentContext::cancel_token) at long awaits
/// to wind down gracefully.
#[async_trait]
pub trait AsAgent: HasAgentData + Send + Sync + 'static {
    /// Constructs a new agent instance.
    fn new(ma: ModularAgent, id: String, spec: AgentSpec) -> Result<Self, AgentError>
    where
        Self: Sized;

    /// Called when configuration values change.
    ///
    /// Override to react to configuration changes at runtime.
    fn configs_changed(&mut self) -> Result<(), AgentError> {
        Ok(())
    }

    /// Called when the agent starts.
    ///
    /// Override for initialization logic or to emit initial values.
    async fn start(&mut self) -> Result<(), AgentError> {
        Ok(())
    }

    /// Called when the agent stops.
    ///
    /// Override for cleanup logic.
    async fn stop(&mut self) -> Result<(), AgentError> {
        Ok(())
    }

    /// Processes an input message.
    ///
    /// Override to implement the agent's main logic.
    ///
    /// This method may be cancelled by being dropped at any await point (see
    /// the [trait-level docs](AsAgent#cancellation-safety)). Long-running
    /// implementations can additionally observe
    /// [`AgentContext::cancel_token`] to abort gracefully when the flow is
    /// cancelled via [`ModularAgent::abort_context`], recording the
    /// interruption as [`AgentError::Cancelled`].
    async fn process(
        &mut self,
        _ctx: AgentContext,
        _port: String,
        _value: AgentValue,
    ) -> Result<(), AgentError> {
        Ok(())
    }
}

#[async_trait]
impl<T: AsAgent> Agent for T {
    fn new(ma: ModularAgent, id: String, spec: AgentSpec) -> Result<Self, AgentError> {
        let mut agent = T::new(ma, id, spec)?;
        agent.mut_data().status = AgentStatus::Init;
        Ok(agent)
    }

    fn ma(&self) -> &ModularAgent {
        &self.data().ma
    }

    fn id(&self) -> &str {
        &self.data().id
    }

    fn spec(&self) -> &AgentSpec {
        &self.data().spec
    }

    fn update_spec(&mut self, value: &Value) -> Result<(), AgentError> {
        self.mut_data().spec.update(value)
    }

    fn status(&self) -> &AgentStatus {
        &self.data().status
    }

    fn def_name(&self) -> &str {
        self.data().spec.def_name.as_str()
    }

    fn configs(&self) -> Result<&AgentConfigs, AgentError> {
        self.data()
            .spec
            .configs
            .as_ref()
            .ok_or(AgentError::NoConfig)
    }

    fn set_config(&mut self, key: String, value: AgentValue) -> Result<(), AgentError> {
        if let Some(configs) = &mut self.mut_data().spec.configs {
            configs.set(key, value);
            self.configs_changed()?;
        }
        Ok(())
    }

    fn set_configs(&mut self, configs: AgentConfigs) -> Result<(), AgentError> {
        self.mut_data().spec.configs = Some(configs);
        self.configs_changed()
    }

    fn preset_id(&self) -> &str {
        &self.data().preset_id
    }

    fn set_preset_id(&mut self, preset_id: String) {
        self.mut_data().preset_id = preset_id;
    }

    async fn start(&mut self) -> Result<(), AgentError> {
        self.mut_data().status = AgentStatus::Start;

        if let Err(e) = <T as AsAgent>::start(self).await {
            self.ma()
                .emit_agent_error(self.id().to_string(), e.to_string());
            return Err(e);
        }

        Ok(())
    }

    async fn stop(&mut self) -> Result<(), AgentError> {
        self.mut_data().status = AgentStatus::Stop;
        <T as AsAgent>::stop(self).await?;
        self.mut_data().status = AgentStatus::Init;
        Ok(())
    }

    async fn process(
        &mut self,
        ctx: AgentContext,
        port: String,
        value: AgentValue,
    ) -> Result<(), AgentError> {
        if let Err(e) = <T as AsAgent>::process(self, ctx.clone(), port, value).await {
            self.ma()
                .emit_agent_error(self.id().to_string(), e.to_string());
            self.ma()
                .send_agent_out(
                    self.id().to_string(),
                    ctx,
                    "err".to_string(),
                    AgentValue::Error(Arc::new(e.clone())),
                )
                .await
                .unwrap_or_else(|e| {
                    log::error!("Failed to send error message for {}: {}", self.id(), e);
                });
            return Err(e);
        }
        Ok(())
    }

    fn get_global_configs(&self) -> Option<AgentConfigs> {
        self.ma().get_global_configs(self.def_name())
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }
}

/// Creates a boxed agent instance from a concrete type.
#[doc(hidden)]
pub fn new_agent_boxed<T: Agent>(
    ma: ModularAgent,
    id: String,
    spec: AgentSpec,
) -> Result<Box<dyn Agent>, AgentError> {
    Ok(Box::new(T::new(ma, id, spec)?))
}

/// Creates an agent based on its definition.
///
/// Looks up the agent definition by name and calls the appropriate constructor.
pub(crate) fn agent_new(
    ma: ModularAgent,
    agent_id: String,
    mut spec: AgentSpec,
) -> Result<Box<dyn Agent>, AgentError> {
    let def;
    {
        let def_name = &spec.def_name;
        let defs = ma.defs.lock().unwrap();
        def = defs
            .get(def_name)
            .ok_or_else(|| AgentError::UnknownDefName(def_name.to_string()))?
            .clone();
    }

    def.reconcile_spec(&mut spec);

    if let Some(new_boxed) = def.new_boxed {
        return new_boxed(ma, agent_id, spec);
    }

    Err(AgentError::UnknownDefKind(def.kind.to_string()))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::AgentConfigs;
    use crate::value::AgentValue;

    #[test]
    fn test_agent_data_new_strips_prefixed_keys() {
        let ma = ModularAgent::init().unwrap();
        let mut configs = AgentConfigs::new();
        configs.set("name".into(), AgentValue::string("hello"));
        configs.set("count".into(), AgentValue::integer(10));
        configs.set("_old_key".into(), AgentValue::string("stale"));
        configs.set("_removed".into(), AgentValue::integer(42));

        let spec = AgentSpec {
            configs: Some(configs),
            ..Default::default()
        };

        let data = AgentData::new(ma.clone(), "test_id".into(), spec);

        let c = data.spec.configs.as_ref().unwrap();
        assert_eq!(c.get_string_or_default("name"), "hello");
        assert_eq!(c.get_integer_or_default("count"), 10);
        assert!(c.get("_old_key").is_err());
        assert!(c.get("_removed").is_err());

        ma.quit();
    }
}