ag-agent 0.20.0

Agentty is an ADE (Agentic Development Environment) for structured, controllable AI-assisted software development.
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
//! Provider operation timing and bounded tool metadata for one execution
//! attempt.

use std::collections::{HashMap, HashSet};
use std::time::{Duration, SystemTime};

use ag_session::AgentKind;
use ag_telemetry::{CaptureToolContent, Context, KeyValue, Outcome, Span, TraceContextExt as _};
use serde_json::Value;

use super::tool_trace::{ToolMetadata, safe_identity};

/// Bounds provider-controlled operation identities retained by one attempt.
const MAX_OPERATIONS: usize = 4096;

/// Tool name for Codex command executions, whose protocol items name no
/// tool. It matches the item type in Codex's `exec` event stream.
const CODEX_COMMAND_TOOL_NAME: &str = "command_execution";

/// Tool name for Codex file changes, whose protocol items name no tool. It
/// matches the item type in Codex's `exec` event stream. Patch content stays
/// excluded under every capture policy.
const CODEX_FILE_CHANGE_TOOL_NAME: &str = "file_change";

/// Retains child spans until matching completion or attempt cancellation.
pub(crate) struct OperationTrace {
    completed: HashSet<String>,
    context: Context,
    operations: HashMap<String, Span>,
    started_at: SystemTime,
}

impl OperationTrace {
    /// Captures the attempt context before reading provider events. Each
    /// operation span repeats the run identity inherited by that context.
    pub(crate) fn new() -> Self {
        Self {
            completed: HashSet::new(),
            context: Context::current(),
            operations: HashMap::new(),
            started_at: SystemTime::now(),
        }
    }

    /// Reads allowlisted operation metadata. Tool content is exported only
    /// under the host's explicit content-capture policy.
    pub(crate) fn observe(&mut self, kind: AgentKind, payload: &Value) {
        if !self.context.span().is_recording() {
            return;
        }

        match kind {
            AgentKind::Codex => self.codex(payload),
            AgentKind::Antigravity => self.antigravity(payload),
            AgentKind::Claude => self.claude(payload),
            AgentKind::Harness => {}
        }
    }

    /// Records terminal items after the caller validates a successful
    /// completion for the active Codex turn and thread. Item identities
    /// deduplicate snapshots against standalone completion notifications.
    pub(crate) fn observe_codex_completed_turn(&mut self, payload: &Value) {
        if !self.context.span().is_recording() {
            return;
        }
        let Some(items) = payload
            .get("params")
            .and_then(|params| params.get("turn"))
            .and_then(|turn| turn.get("items"))
            .and_then(Value::as_array)
        else {
            return;
        };

        for item in items {
            self.codex_item(item, true);
        }
    }

    fn codex(&mut self, payload: &Value) {
        let Some(method) = payload.get("method").and_then(Value::as_str) else {
            return;
        };
        if !matches!(method, "item/started" | "item/completed") {
            return;
        }
        let Some(item) = payload.get("params").and_then(|params| params.get("item")) else {
            return;
        };

        self.codex_item(item, method == "item/completed");
    }

    fn codex_item(&mut self, item: &Value, completed: bool) {
        let Some(id) = item.get("id").and_then(Value::as_str) else {
            return;
        };
        let category = match item.get("type").and_then(Value::as_str) {
            Some("commandExecution" | "command_execution") => "command",
            Some("fileChange" | "file_change") => "file_change",
            Some("mcpToolCall" | "mcp_tool_call") => "mcp",
            Some("dynamicToolCall" | "dynamic_tool_call") => "dynamic_tool",
            Some("webSearch" | "web_search") => "web_search",
            Some("reasoning") => "reasoning",
            Some("agentMessage" | "agent_message") => "response",
            Some("contextCompaction" | "context_compaction") => "compaction",
            Some("collabAgentToolCall" | "collab_agent_tool_call") => "subagent",
            Some("imageGeneration" | "image_generation") => "image_generation",
            _ => return,
        };
        let outcome = completed.then(|| Self::outcome(item));
        let mut attributes = Vec::new();
        if category == "compaction" {
            attributes.push(KeyValue::new(
                "agentty.compaction.trigger",
                "provider_native",
            ));
        }
        if let Some(exit_code) = item.get("exitCode").and_then(Value::as_i64) {
            attributes.push(KeyValue::new("agentty.provider.exit_code", exit_code));
        }
        if category == "file_change" {
            attributes.push(KeyValue::new(
                "gen_ai.tool.name",
                CODEX_FILE_CHANGE_TOOL_NAME,
            ));
        }
        if matches!(category, "command" | "mcp" | "dynamic_tool") {
            attributes.extend(
                ToolMetadata {
                    command: item.get("command").and_then(Value::as_str),
                    input: item.get("arguments"),
                    name: item
                        .get("tool")
                        .and_then(Value::as_str)
                        .or((category == "command").then_some(CODEX_COMMAND_TOOL_NAME)),
                    output: ["aggregatedOutput", "result", "contentItems", "error"]
                        .into_iter()
                        .filter_map(|field| item.get(field))
                        .find(|value| !value.is_null()),
                }
                .attributes(self.capture_content()),
            );
        }
        self.record(
            id,
            category,
            outcome,
            item.get("durationMs").and_then(Value::as_f64),
            attributes,
        );
    }

    fn antigravity(&mut self, payload: &Value) {
        if payload.get("event").and_then(Value::as_str) != Some("step_update") {
            return;
        }
        let Some(step) = payload.get("step_update") else {
            return;
        };
        let Some(index) = step.get("step_index").and_then(Value::as_u64) else {
            return;
        };
        let category = match step.get("step_type").and_then(Value::as_str) {
            Some("tool")
                if step
                    .get("subagent_info")
                    .is_some_and(|info| !info.is_null()) =>
            {
                "subagent"
            }
            Some("tool") => "tool",
            Some("agent_response") => "response",
            Some("reasoning" | "thought") => "reasoning",
            Some("context_compaction" | "context-compaction" | "context_compression") => {
                "compaction"
            }
            Some("checkpoint") => "checkpoint",
            _ => return,
        };
        let outcome = match step.get("state").and_then(Value::as_str) {
            Some(state) if state.eq_ignore_ascii_case("active") => None,
            Some(state) if state.eq_ignore_ascii_case("done") => {
                Some(Self::outcome(step.get("tool_info").unwrap_or(step)))
            }
            _ => return,
        };
        let mut attributes = Self::usage(step.get("usage"));
        if matches!(category, "tool" | "subagent") {
            attributes.extend(
                ToolMetadata {
                    name: step.get("tool_name").and_then(Value::as_str),
                    ..ToolMetadata::default()
                }
                .attributes(self.capture_content()),
            );
        }
        self.record(
            &index.to_string(),
            category,
            outcome,
            step.get("duration_seconds")
                .and_then(Value::as_f64)
                .map(|seconds| seconds * 1000.0),
            attributes,
        );
    }

    fn claude(&mut self, payload: &Value) {
        let message = if payload.get("type").and_then(Value::as_str) == Some("message") {
            payload
        } else if let Some(message) = payload.get("message") {
            message
        } else {
            return;
        };
        let Some(blocks) = message.get("content").and_then(Value::as_array) else {
            return;
        };
        for block in blocks {
            match block.get("type").and_then(Value::as_str) {
                Some("tool_use") => {
                    if let Some(id) = block.get("id").and_then(Value::as_str) {
                        let category = match block.get("name").and_then(Value::as_str) {
                            Some("Bash") => "command",
                            Some("Read") => "read",
                            Some("Edit" | "Write" | "MultiEdit") => "file_change",
                            Some("Grep" | "Glob") => "search",
                            Some("WebFetch") => "fetch",
                            Some("WebSearch") => "web_search",
                            Some("Agent" | "Task") => "subagent",
                            _ => "tool",
                        };
                        let input = if category == "subagent"
                            || block.get("name").and_then(Value::as_str) == Some("StructuredOutput")
                        {
                            None
                        } else {
                            block.get("input")
                        };
                        let attributes = ToolMetadata {
                            command: input
                                .and_then(|input| input.get("command"))
                                .and_then(Value::as_str),
                            input,
                            name: block.get("name").and_then(Value::as_str),
                            ..ToolMetadata::default()
                        }
                        .attributes(self.capture_content());
                        self.record(id, category, None, None, attributes);
                    }
                }
                Some("tool_result") => {
                    if let Some(id) = block.get("tool_use_id").and_then(Value::as_str) {
                        let outcome =
                            if block.get("is_error").and_then(Value::as_bool) == Some(true) {
                                Outcome::Failed
                            } else {
                                Outcome::Completed
                            };
                        let attributes = ToolMetadata {
                            output: block.get("content"),
                            ..ToolMetadata::default()
                        }
                        .attributes(self.capture_content());
                        self.record(id, "tool", Some(outcome), None, attributes);
                    }
                }
                _ => {}
            }
        }
    }

    fn record(
        &mut self,
        id: &str,
        category: &'static str,
        outcome: Option<Outcome>,
        duration_ms: Option<f64>,
        attributes: Vec<KeyValue>,
    ) {
        if id.is_empty() || id.len() > 256 || self.completed.contains(id) {
            return;
        }
        let duration_ms = duration_ms.filter(|duration| duration.is_finite() && *duration >= 0.0);
        let span = self.operations.remove(id);
        if span.is_none() && self.operations.len() + self.completed.len() >= MAX_OPERATIONS {
            return;
        }
        let span = span.unwrap_or_else(|| {
            let now = SystemTime::now();
            let reported = outcome
                .and(duration_ms)
                .and_then(|duration| Duration::try_from_secs_f64(duration / 1000.0).ok());
            let start = reported.map_or(now, |duration| {
                now - duration.min(now.duration_since(self.started_at).unwrap_or_default())
            });
            let _guard = self.context.clone().attach();
            let name = match category {
                "response" => "agent.response",
                "reasoning" => "agent.reasoning",
                "compaction" => "agent.compaction",
                "checkpoint" => "agent.checkpoint",
                "subagent" => "agent.subagent",
                _ => "agent.tool",
            };
            let span = Span::operation_at(name, start);
            span.attribute("agentty.provider.operation.type", category);
            if (name == "agent.tool" || name == "agent.subagent")
                && let Some(id) = safe_identity(id)
            {
                span.attribute("gen_ai.tool.call.id", id.to_string());
            }
            span.attribute(
                "agentty.timing.source",
                if reported.is_some() {
                    "provider"
                } else if outcome.is_some() {
                    "completion"
                } else {
                    "lifecycle"
                },
            );
            span
        });
        if let Some(duration) = duration_ms {
            span.attribute("agentty.provider.duration_ms", duration);
        }
        for attribute in attributes {
            span.context().span().set_attribute(attribute);
        }
        if let Some(outcome) = outcome {
            span.attribute("agentty.provider.completion.observed", true);
            span.finish(outcome);
            self.completed.insert(id.to_string());
        } else {
            self.operations.insert(id.to_string(), span);
        }
    }

    fn outcome(value: &Value) -> Outcome {
        if matches!(
            value.get("status").and_then(Value::as_str),
            Some("canceled" | "cancelled" | "interrupted")
        ) {
            Outcome::Canceled
        } else if matches!(
            value.get("status").and_then(Value::as_str),
            Some("failed" | "declined" | "denied")
        ) || value.get("error").is_some_and(|error| !error.is_null())
            || value.get("success").and_then(Value::as_bool) == Some(false)
            || value
                .get("exitCode")
                .and_then(Value::as_i64)
                .is_some_and(|code| code != 0)
        {
            Outcome::Failed
        } else {
            Outcome::Completed
        }
    }

    fn capture_content(&self) -> bool {
        self.context
            .get::<CaptureToolContent>()
            .is_some_and(|policy| policy.0)
    }

    fn usage(usage: Option<&Value>) -> Vec<KeyValue> {
        let Some(usage) = usage else {
            return Vec::new();
        };

        [
            ("input_tokens", "gen_ai.usage.input_tokens"),
            ("output_tokens", "gen_ai.usage.output_tokens"),
            ("cache_read_tokens", "gen_ai.usage.cache_read.input_tokens"),
            ("thinking_tokens", "gen_ai.usage.reasoning.output_tokens"),
        ]
        .into_iter()
        .filter_map(|(field, key)| {
            usage
                .get(field)
                .and_then(Value::as_u64)
                .and_then(|tokens| i64::try_from(tokens).ok())
                .map(|tokens| KeyValue::new(key, tokens))
        })
        .collect()
    }
}

impl Drop for OperationTrace {
    fn drop(&mut self) {
        for span in self.operations.values() {
            span.attribute("agentty.provider.completion.observed", false);
            span.attribute("agentty.timing.incomplete", true);
        }
    }
}

#[cfg(test)]
#[path = "trace_test.rs"]
mod tests;