ai-agents-observability 1.0.0-rc.15

Observability and tracing for AI Agents framework
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
use crate::event::{EventStatus, EventType, ObservationPurpose};
use crate::manager::ObservabilityManager;
use ai_agents_core::{AgentError, AgentResponse, KeyFact};
use ai_agents_hitl::{ApprovalRequest, ApprovalResult, ApprovalTrigger};
use ai_agents_hooks::AgentHooks;
use ai_agents_memory::{MemoryBudgetEvent, MemoryCompressEvent, MemoryEvictEvent};
use ai_agents_relationships::{DimensionChange, Relationship, RelationshipEvent};
use async_trait::async_trait;
use serde_json::Value;
use std::collections::HashMap;
use std::sync::Arc;

/// AgentHooks implementation that records lifecycle events not covered by wrappers.
pub struct ObservabilityHooks {
    manager: Arc<ObservabilityManager>,
}

impl ObservabilityHooks {
    /// Creates lifecycle hooks backed by a shared manager.
    pub fn new(manager: Arc<ObservabilityManager>) -> Self {
        Self { manager }
    }

    fn record(
        &self,
        event_type: EventType,
        purpose: ObservationPurpose,
        tags: HashMap<String, String>,
    ) {
        self.manager.record_lifecycle_event(
            event_type,
            purpose,
            EventStatus::Success,
            0,
            tags,
            None,
        );
    }
}

fn approval_trigger_label(trigger: &ApprovalTrigger) -> (&'static str, Option<String>) {
    match trigger {
        ApprovalTrigger::Tool { name, .. } => ("tool", Some(name.clone())),
        ApprovalTrigger::Condition { name, .. } => ("condition", Some(name.clone())),
        ApprovalTrigger::State { to, .. } => ("state", Some(to.clone())),
    }
}

fn approval_result_label(result: &ApprovalResult) -> &'static str {
    match result {
        ApprovalResult::Approved => "approved",
        ApprovalResult::Rejected { .. } => "rejected",
        ApprovalResult::Modified { .. } => "modified",
        ApprovalResult::Timeout => "timeout",
    }
}

#[async_trait]
impl AgentHooks for ObservabilityHooks {
    async fn on_state_transition(&self, from: Option<&str>, to: &str, reason: &str) {
        let mut tags = HashMap::new();
        tags.insert("reason".to_string(), reason.to_string());
        self.record(
            EventType::StateTransition {
                from: from.map(str::to_string),
                to: to.to_string(),
            },
            ObservationPurpose::StateTransitionEvaluation,
            tags,
        );
    }

    async fn on_error(&self, error: &AgentError) {
        self.manager.record_lifecycle_event(
            EventType::Error,
            ObservationPurpose::default(),
            EventStatus::Error,
            0,
            HashMap::new(),
            Some(serde_json::json!({"kind": "agent_error", "message": error.to_string()})),
        );
    }

    async fn on_approval_requested(&self, request: &ApprovalRequest) {
        if !self.manager.config().latency.track_hitl {
            return;
        }
        let (trigger, detail) = approval_trigger_label(&request.trigger);
        let mut tags = HashMap::new();
        tags.insert("request_id".to_string(), request.id.clone());
        if let Some(detail) = detail {
            tags.insert("trigger_id".to_string(), detail);
        }
        self.record(
            EventType::HitlApproval {
                trigger: trigger.to_string(),
            },
            ObservationPurpose::HitlLocalization,
            tags,
        );
    }

    async fn on_approval_result(&self, request_id: &str, result: &ApprovalResult) {
        if !self.manager.config().latency.track_hitl {
            return;
        }
        let mut tags = HashMap::new();
        tags.insert("request_id".to_string(), request_id.to_string());
        tags.insert(
            "result".to_string(),
            approval_result_label(result).to_string(),
        );
        self.record(
            EventType::HitlApproval {
                trigger: "result".to_string(),
            },
            ObservationPurpose::HitlLocalization,
            tags,
        );
    }

    async fn on_memory_compress(&self, event: &MemoryCompressEvent) {
        self.manager.record_lifecycle_event(
            EventType::MemoryOperation {
                operation: "compress".to_string(),
            },
            ObservationPurpose::Summarization,
            EventStatus::Success,
            0,
            HashMap::new(),
            Some(serde_json::json!({
                "messages_compressed": event.messages_compressed,
                "compression_ratio": event.compression_ratio,
            })),
        );
    }

    async fn on_memory_evict(&self, event: &MemoryEvictEvent) {
        self.manager.record_lifecycle_event(
            EventType::MemoryOperation {
                operation: "evict".to_string(),
            },
            ObservationPurpose::Summarization,
            EventStatus::Success,
            0,
            HashMap::new(),
            Some(serde_json::json!({
                "messages_evicted": event.messages_evicted,
                "reason": format!("{:?}", event.reason),
            })),
        );
    }

    async fn on_memory_budget_warning(&self, event: &MemoryBudgetEvent) {
        let mut tags = HashMap::new();
        tags.insert("warning".to_string(), "memory_budget".to_string());
        self.manager.record_lifecycle_event(
            EventType::MemoryOperation {
                operation: "budget_warning".to_string(),
            },
            ObservationPurpose::Summarization,
            EventStatus::Success,
            0,
            tags,
            Some(serde_json::json!({
                "component": event.component,
                "used_tokens": event.used_tokens,
                "budget_tokens": event.budget_tokens,
                "usage_percent": event.usage_percent,
            })),
        );
    }

    async fn on_delegate_start(&self, agent_id: &str, state: &str) {
        if !self.manager.config().latency.track_orchestration {
            return;
        }
        let mut tags = HashMap::new();
        tags.insert("agent_id".to_string(), agent_id.to_string());
        tags.insert("state".to_string(), state.to_string());
        self.record(
            EventType::Orchestration {
                pattern: "delegate".to_string(),
            },
            ObservationPurpose::OrchestrationRouting,
            tags,
        );
    }

    async fn on_delegate_complete(&self, agent_id: &str, state: &str, duration_ms: u64) {
        if !self.manager.config().latency.track_orchestration {
            return;
        }
        let mut tags = HashMap::new();
        tags.insert("agent_id".to_string(), agent_id.to_string());
        tags.insert("state".to_string(), state.to_string());
        self.manager.record_lifecycle_event(
            EventType::Orchestration {
                pattern: "delegate".to_string(),
            },
            ObservationPurpose::OrchestrationRouting,
            EventStatus::Success,
            duration_ms,
            tags,
            None,
        );
    }

    async fn on_concurrent_complete(&self, agent_ids: &[String], strategy: &str, duration_ms: u64) {
        if !self.manager.config().latency.track_orchestration {
            return;
        }
        self.manager.record_lifecycle_event(
            EventType::Orchestration {
                pattern: "concurrent".to_string(),
            },
            ObservationPurpose::OrchestrationAggregation,
            EventStatus::Success,
            duration_ms,
            HashMap::new(),
            Some(serde_json::json!({"agents": agent_ids, "strategy": strategy})),
        );
    }

    async fn on_group_chat_round(&self, round: u32, speaker: &str, _content: &str) {
        if !self.manager.config().latency.track_orchestration {
            return;
        }
        self.manager.record_lifecycle_event(
            EventType::Orchestration {
                pattern: "group_chat".to_string(),
            },
            ObservationPurpose::OrchestrationConversation,
            EventStatus::Success,
            0,
            HashMap::new(),
            Some(serde_json::json!({"round": round, "speaker": speaker})),
        );
    }

    async fn on_pipeline_stage(&self, stage: usize, agent_id: &str, duration_ms: u64) {
        if !self.manager.config().latency.track_orchestration {
            return;
        }
        self.manager.record_lifecycle_event(
            EventType::Orchestration {
                pattern: "pipeline".to_string(),
            },
            ObservationPurpose::OrchestrationRouting,
            EventStatus::Success,
            duration_ms,
            HashMap::new(),
            Some(serde_json::json!({"stage": stage, "agent_id": agent_id})),
        );
    }

    async fn on_pipeline_complete(&self, stages: usize, duration_ms: u64) {
        if !self.manager.config().latency.track_orchestration {
            return;
        }
        self.manager.record_lifecycle_event(
            EventType::Orchestration {
                pattern: "pipeline".to_string(),
            },
            ObservationPurpose::OrchestrationAggregation,
            EventStatus::Success,
            duration_ms,
            HashMap::new(),
            Some(serde_json::json!({"stages": stages})),
        );
    }

    async fn on_handoff_start(&self, initial_agent: &str) {
        if !self.manager.config().latency.track_orchestration {
            return;
        }
        self.manager.record_lifecycle_event(
            EventType::Orchestration {
                pattern: "handoff".to_string(),
            },
            ObservationPurpose::OrchestrationRouting,
            EventStatus::Success,
            0,
            HashMap::new(),
            Some(serde_json::json!({"initial_agent": initial_agent})),
        );
    }

    async fn on_handoff(&self, from: &str, to: &str, reason: &str) {
        if !self.manager.config().latency.track_orchestration {
            return;
        }
        self.manager.record_lifecycle_event(
            EventType::Orchestration {
                pattern: "handoff".to_string(),
            },
            ObservationPurpose::OrchestrationRouting,
            EventStatus::Success,
            0,
            HashMap::new(),
            Some(serde_json::json!({"from": from, "to": to, "reason": reason})),
        );
    }

    async fn on_persona_evolve(
        &self,
        field: &str,
        _old_value: &Value,
        _new_value: &Value,
        reason: Option<&str>,
    ) {
        self.manager.record_lifecycle_event(
            EventType::PersonaEvent {
                event: "evolve".to_string(),
            },
            ObservationPurpose::Other("persona".to_string()),
            EventStatus::Success,
            0,
            HashMap::new(),
            Some(serde_json::json!({"field": field, "reason": reason})),
        );
    }

    async fn on_secret_revealed(&self, _content: &str) {
        self.record(
            EventType::PersonaEvent {
                event: "secret_revealed".to_string(),
            },
            ObservationPurpose::Other("persona".to_string()),
            HashMap::new(),
        );
    }

    async fn on_facts_extracted(&self, actor_id: &str, facts: &[KeyFact]) {
        self.manager.record_lifecycle_event(
            EventType::FactsEvent {
                event: "extracted".to_string(),
            },
            ObservationPurpose::FactsExtraction,
            EventStatus::Success,
            0,
            HashMap::new(),
            Some(serde_json::json!({"actor_id": actor_id, "count": facts.len()})),
        );
    }

    async fn on_actor_memory_loaded(&self, actor_id: &str, fact_count: usize) {
        self.manager.record_lifecycle_event(
            EventType::FactsEvent {
                event: "actor_memory_loaded".to_string(),
            },
            ObservationPurpose::FactsExtraction,
            EventStatus::Success,
            0,
            HashMap::new(),
            Some(serde_json::json!({"actor_id": actor_id, "count": fact_count})),
        );
    }

    async fn on_relationship_loaded(&self, actor_id: &str, _relationship: &Relationship) {
        self.manager.record_lifecycle_event(
            EventType::RelationshipEvent {
                event: "loaded".to_string(),
            },
            ObservationPurpose::RelationshipUpdate,
            EventStatus::Success,
            0,
            HashMap::new(),
            Some(serde_json::json!({"actor_id": actor_id})),
        );
    }

    async fn on_relationship_change(&self, actor_id: &str, changes: &[DimensionChange]) {
        self.manager.record_lifecycle_event(
            EventType::RelationshipEvent {
                event: "changed".to_string(),
            },
            ObservationPurpose::RelationshipUpdate,
            EventStatus::Success,
            0,
            HashMap::new(),
            Some(serde_json::json!({"actor_id": actor_id, "changes": changes.len()})),
        );
    }

    async fn on_notable_event(&self, actor_id: &str, event: &RelationshipEvent) {
        self.manager.record_lifecycle_event(
            EventType::RelationshipEvent {
                event: "notable_event".to_string(),
            },
            ObservationPurpose::RelationshipUpdate,
            EventStatus::Success,
            0,
            HashMap::new(),
            Some(serde_json::json!({
                "actor_id": actor_id,
                "significance": event.significance,
            })),
        );
    }

    async fn on_response(&self, _response: &AgentResponse) {}
}