tirea-agentos 0.5.0

Agent runtime with streaming LLM integration, sub-agent orchestration, and context window management
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
use crate::contracts::runtime::behavior::{AgentBehavior, ReadOnlyContext};
use crate::contracts::runtime::phase::{
    ActionSet, AfterInferenceAction, AfterToolExecuteAction, BeforeInferenceAction,
    BeforeToolExecuteAction, LifecycleAction,
};
use async_trait::async_trait;
use std::collections::{BinaryHeap, HashMap};
use std::sync::Arc;

/// Error returned when plugin ordering constraints form a cycle.
#[derive(Debug, Clone)]
pub struct PluginOrderingCycleError {
    pub involved: Vec<String>,
}

impl std::fmt::Display for PluginOrderingCycleError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "plugin ordering cycle detected among: {}",
            self.involved.join(", ")
        )
    }
}

impl std::error::Error for PluginOrderingCycleError {}

/// Compose multiple behaviors into a single [`AgentBehavior`].
///
/// Returns an error if ordering constraints form a cycle.
pub fn compose_behaviors(
    id: impl Into<String>,
    behaviors: Vec<Arc<dyn AgentBehavior>>,
) -> Result<Arc<dyn AgentBehavior>, PluginOrderingCycleError> {
    match behaviors.len() {
        0 => Ok(Arc::new(crate::contracts::runtime::behavior::NoOpBehavior)),
        1 => Ok(behaviors.into_iter().next().unwrap()),
        _ => Ok(Arc::new(CompositeBehavior::new(id, behaviors)?)),
    }
}

/// An [`AgentBehavior`] that composes multiple sub-behaviors.
///
/// Each phase hook executes sub-behaviors sequentially in topological order.
pub(crate) struct CompositeBehavior {
    id: String,
    behaviors: Vec<Arc<dyn AgentBehavior>>,
}

impl CompositeBehavior {
    pub(crate) fn new(
        id: impl Into<String>,
        behaviors: Vec<Arc<dyn AgentBehavior>>,
    ) -> Result<Self, PluginOrderingCycleError> {
        let sorted = topological_sort(&behaviors)?;
        Ok(Self {
            id: id.into(),
            behaviors: sorted,
        })
    }
}

#[async_trait]
impl AgentBehavior for CompositeBehavior {
    fn id(&self) -> &str {
        &self.id
    }

    fn behavior_ids(&self) -> Vec<&str> {
        self.behaviors
            .iter()
            .flat_map(|b| b.behavior_ids())
            .collect()
    }

    fn configure(&self, config: &mut tirea_contract::runtime::run::config::AgentRunConfig) {
        for b in &self.behaviors {
            b.configure(config);
        }
    }

    async fn run_start(&self, ctx: &ReadOnlyContext<'_>) -> ActionSet<LifecycleAction> {
        let mut combined = ActionSet::empty();
        for b in &self.behaviors {
            combined = combined.and(b.run_start(ctx).await);
        }
        combined
    }

    async fn step_start(&self, ctx: &ReadOnlyContext<'_>) -> ActionSet<LifecycleAction> {
        let mut combined = ActionSet::empty();
        for b in &self.behaviors {
            combined = combined.and(b.step_start(ctx).await);
        }
        combined
    }

    async fn before_inference(
        &self,
        ctx: &ReadOnlyContext<'_>,
    ) -> ActionSet<BeforeInferenceAction> {
        let mut combined = ActionSet::empty();
        for b in &self.behaviors {
            combined = combined.and(b.before_inference(ctx).await);
        }
        combined
    }

    async fn after_inference(&self, ctx: &ReadOnlyContext<'_>) -> ActionSet<AfterInferenceAction> {
        let mut combined = ActionSet::empty();
        for b in &self.behaviors {
            combined = combined.and(b.after_inference(ctx).await);
        }
        combined
    }

    async fn before_tool_execute(
        &self,
        ctx: &ReadOnlyContext<'_>,
    ) -> ActionSet<BeforeToolExecuteAction> {
        let mut combined = ActionSet::empty();
        for b in &self.behaviors {
            combined = combined.and(b.before_tool_execute(ctx).await);
        }
        combined
    }

    async fn after_tool_execute(
        &self,
        ctx: &ReadOnlyContext<'_>,
    ) -> ActionSet<AfterToolExecuteAction> {
        let mut combined = ActionSet::empty();
        for b in &self.behaviors {
            combined = combined.and(b.after_tool_execute(ctx).await);
        }
        combined
    }

    async fn step_end(&self, ctx: &ReadOnlyContext<'_>) -> ActionSet<LifecycleAction> {
        let mut combined = ActionSet::empty();
        for b in &self.behaviors {
            combined = combined.and(b.step_end(ctx).await);
        }
        combined
    }

    async fn run_end(&self, ctx: &ReadOnlyContext<'_>) -> ActionSet<LifecycleAction> {
        let mut combined = ActionSet::empty();
        for b in &self.behaviors {
            combined = combined.and(b.run_end(ctx).await);
        }
        combined
    }
}

/// Kahn's algorithm with stable tie-breaking by original index.
fn topological_sort(
    behaviors: &[Arc<dyn AgentBehavior>],
) -> Result<Vec<Arc<dyn AgentBehavior>>, PluginOrderingCycleError> {
    let n = behaviors.len();
    if n <= 1 {
        return Ok(behaviors.to_vec());
    }

    let mut id_to_idx: HashMap<&str, usize> = HashMap::with_capacity(n);
    for (i, b) in behaviors.iter().enumerate() {
        id_to_idx.entry(b.id()).or_insert(i);
    }

    let mut adj: Vec<Vec<usize>> = vec![Vec::new(); n];
    let mut in_degree: Vec<usize> = vec![0; n];

    for (i, b) in behaviors.iter().enumerate() {
        let ord = b.ordering();
        for &dep_id in ord.after {
            if let Some(&dep_idx) = id_to_idx.get(dep_id) {
                if dep_idx != i {
                    adj[dep_idx].push(i);
                    in_degree[i] += 1;
                }
            }
        }
        for &dep_id in ord.before {
            if let Some(&dep_idx) = id_to_idx.get(dep_id) {
                if dep_idx != i {
                    adj[i].push(dep_idx);
                    in_degree[dep_idx] += 1;
                }
            }
        }
    }

    let mut heap: BinaryHeap<std::cmp::Reverse<usize>> = BinaryHeap::new();
    for (i, deg) in in_degree.iter().enumerate() {
        if *deg == 0 {
            heap.push(std::cmp::Reverse(i));
        }
    }

    let mut sorted: Vec<Arc<dyn AgentBehavior>> = Vec::with_capacity(n);
    while let Some(std::cmp::Reverse(idx)) = heap.pop() {
        sorted.push(Arc::clone(&behaviors[idx]));
        for &next in &adj[idx] {
            in_degree[next] -= 1;
            if in_degree[next] == 0 {
                heap.push(std::cmp::Reverse(next));
            }
        }
    }

    if sorted.len() != n {
        let involved: Vec<String> = behaviors
            .iter()
            .enumerate()
            .filter(|(i, _)| in_degree[*i] > 0)
            .map(|(_, b)| b.id().to_string())
            .collect();
        return Err(PluginOrderingCycleError { involved });
    }

    Ok(sorted)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::contracts::runtime::behavior::PluginOrdering;
    use crate::contracts::runtime::phase::{BeforeInferenceAction, Phase};
    use crate::contracts::RunPolicy;
    use serde_json::json;
    use tirea_state::DocCell;

    struct ContextBehavior {
        id: String,
        text: String,
    }

    #[async_trait]
    impl AgentBehavior for ContextBehavior {
        fn id(&self) -> &str {
            &self.id
        }
        async fn before_inference(
            &self,
            _ctx: &ReadOnlyContext<'_>,
        ) -> ActionSet<BeforeInferenceAction> {
            ActionSet::single(BeforeInferenceAction::AddContextMessage(
                tirea_contract::runtime::inference::ContextMessage {
                    key: self.id.clone(),
                    role: tirea_contract::thread::Role::System,
                    content: self.text.clone(),
                    visibility: tirea_contract::thread::Visibility::Internal,
                    cooldown_turns: 0,
                    target: Default::default(),
                    consume_after_emit: false,
                },
            ))
        }
    }

    struct OrderedBehavior {
        id: &'static str,
        text: String,
        ord: PluginOrdering,
    }

    #[async_trait]
    impl AgentBehavior for OrderedBehavior {
        fn id(&self) -> &str {
            self.id
        }
        fn ordering(&self) -> PluginOrdering {
            self.ord.clone()
        }
        async fn before_inference(
            &self,
            _ctx: &ReadOnlyContext<'_>,
        ) -> ActionSet<BeforeInferenceAction> {
            ActionSet::single(BeforeInferenceAction::AddContextMessage(
                tirea_contract::runtime::inference::ContextMessage::session(
                    format!("ordered:{}", self.id),
                    self.text.clone(),
                ),
            ))
        }
    }

    fn make_ctx<'a>(doc: &'a DocCell, rp: &'a RunPolicy, phase: Phase) -> ReadOnlyContext<'a> {
        ReadOnlyContext::new(phase, "t1", &[], rp, doc)
    }

    fn extract_texts(actions: ActionSet<BeforeInferenceAction>) -> Vec<String> {
        actions
            .into_vec()
            .into_iter()
            .filter_map(|a| match a {
                BeforeInferenceAction::AddContextMessage(message) => Some(message.content),
                _ => None,
            })
            .collect()
    }

    #[tokio::test]
    async fn composite_merges_actions() {
        let b: Vec<Arc<dyn AgentBehavior>> = vec![
            Arc::new(ContextBehavior {
                id: "a".into(),
                text: "A".into(),
            }),
            Arc::new(ContextBehavior {
                id: "b".into(),
                text: "B".into(),
            }),
        ];
        let c = CompositeBehavior::new("t", b).unwrap();
        let doc = DocCell::new(json!({}));
        let rp = RunPolicy::new();
        assert_eq!(
            c.before_inference(&make_ctx(&doc, &rp, Phase::BeforeInference))
                .await
                .len(),
            2
        );
    }

    #[test]
    fn compose_behaviors_empty_returns_noop() {
        assert_eq!(compose_behaviors("t", vec![]).unwrap().id(), "noop");
    }

    #[test]
    fn compose_behaviors_single_passthrough() {
        let input = Arc::new(ContextBehavior {
            id: "s".into(),
            text: "".into(),
        }) as Arc<dyn AgentBehavior>;
        let out = compose_behaviors("x", vec![input.clone()]).unwrap();
        assert!(Arc::ptr_eq(&out, &input));
    }

    #[test]
    fn topological_sort_preserves_order_without_constraints() {
        let b: Vec<Arc<dyn AgentBehavior>> = vec![
            Arc::new(ContextBehavior {
                id: "c".into(),
                text: "".into(),
            }),
            Arc::new(ContextBehavior {
                id: "a".into(),
                text: "".into(),
            }),
        ];
        let sorted = topological_sort(&b).unwrap();
        let ids: Vec<&str> = sorted.iter().map(|x| x.id()).collect();
        assert_eq!(ids, vec!["c", "a"]);
    }

    #[test]
    fn topological_sort_after_constraint() {
        let b: Vec<Arc<dyn AgentBehavior>> = vec![
            Arc::new(OrderedBehavior {
                id: "B",
                text: "".into(),
                ord: PluginOrdering::after(&["A"]),
            }),
            Arc::new(OrderedBehavior {
                id: "A",
                text: "".into(),
                ord: PluginOrdering::NONE,
            }),
        ];
        let sorted = topological_sort(&b).unwrap();
        let ids: Vec<&str> = sorted.iter().map(|x| x.id()).collect();
        assert_eq!(ids, vec!["A", "B"]);
    }

    #[test]
    fn topological_sort_cycle_detected() {
        let b: Vec<Arc<dyn AgentBehavior>> = vec![
            Arc::new(OrderedBehavior {
                id: "A",
                text: "".into(),
                ord: PluginOrdering::after(&["B"]),
            }),
            Arc::new(OrderedBehavior {
                id: "B",
                text: "".into(),
                ord: PluginOrdering::after(&["A"]),
            }),
        ];
        assert!(topological_sort(&b).is_err());
    }

    #[tokio::test]
    async fn ordering_constraint_affects_action_order() {
        let b: Vec<Arc<dyn AgentBehavior>> = vec![
            Arc::new(OrderedBehavior {
                id: "B",
                text: "B".into(),
                ord: PluginOrdering::after(&["A"]),
            }),
            Arc::new(OrderedBehavior {
                id: "A",
                text: "A".into(),
                ord: PluginOrdering::NONE,
            }),
        ];
        let c = CompositeBehavior::new("t", b).unwrap();
        let doc = DocCell::new(json!({}));
        let rp = RunPolicy::new();
        let texts = extract_texts(
            c.before_inference(&make_ctx(&doc, &rp, Phase::BeforeInference))
                .await,
        );
        assert_eq!(texts, vec!["A", "B"]);
    }
}