Skip to main content

vtcode_core/core/agent/
task.rs

1//! Task-related data structures shared across the agent runner modules.
2
3use crate::exec::events::ThreadCompletionSubtype;
4use crate::exec::events::ThreadEvent;
5use serde::{Deserialize, Serialize};
6use std::fmt;
7
8/// Task specification consumed by the benchmark/autonomous runner.
9#[derive(Debug, Clone, Serialize, Deserialize)]
10pub struct Task {
11    /// Stable identifier for reporting.
12    pub id: String,
13    /// Human-readable task title displayed in progress messages.
14    pub title: String,
15    /// High-level description of the task objective.
16    pub description: String,
17    /// Optional explicit instructions appended to the conversation.
18    #[serde(default, skip_serializing_if = "Option::is_none")]
19    pub instructions: Option<String>,
20}
21
22impl Task {
23    /// Construct a task with the provided metadata.
24    pub fn new(id: String, title: String, description: String) -> Self {
25        Self { id, title, description, instructions: None }
26    }
27}
28
29/// Context entry supplied alongside the benchmark task.
30#[derive(Debug, Clone, Serialize, Deserialize)]
31pub struct ContextItem {
32    /// Identifier used when referencing the context in prompts.
33    pub id: String,
34    /// Raw textual content exposed to the agent.
35    pub content: String,
36}
37
38#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
39#[serde(rename_all = "snake_case")]
40pub enum TaskOutcome {
41    Success,
42    StoppedNoAction,
43    TurnLimitReached {
44        max_turns: usize,
45        actual_turns: usize,
46    },
47    BudgetLimitReached {
48        max_budget_usd: f64,
49        actual_cost_usd: f64,
50    },
51    /// Legacy outcome of the removed per-turn tool-loop budget, kept so older
52    /// serialized artifacts still deserialize. No longer produced by the
53    /// config-driven budget; a rate-limit safeguard halt may still construct
54    /// it with `max_tool_loops: 0`.
55    ToolLoopLimitReached {
56        max_tool_loops: usize,
57        actual_tool_loops: usize,
58    },
59    LoopDetected,
60    Cancelled,
61    HandedOff {
62        target: String,
63    },
64    Escalated {
65        reason: String,
66        tool_name: String,
67    },
68    /// The provider declined the request (`FinishReason::Refusal`). Terminal
69    /// for the prompt: resending it is refused again. `reason` is the
70    /// user-facing notice from [`crate::core::agent::refusal::refusal_reason`].
71    Refused {
72        reason: String,
73    },
74    Failed {
75        reason: String,
76        /// What was accomplished before the failure occurred.
77        #[serde(default, skip_serializing_if = "Vec::is_empty")]
78        accomplished: Vec<String>,
79        /// Optional suggestion for recovery or escalation.
80        #[serde(default, skip_serializing_if = "Option::is_none")]
81        recovery_suggestion: Option<String>,
82        /// Optional path to preserved state for task resume.
83        #[serde(default, skip_serializing_if = "Option::is_none")]
84        checkpoint_path: Option<String>,
85    },
86    Unknown,
87}
88
89impl TaskOutcome {
90    pub fn is_success(&self) -> bool {
91        matches!(self, Self::Success | Self::StoppedNoAction)
92    }
93
94    pub fn is_hard_block(&self) -> bool {
95        matches!(self, Self::ToolLoopLimitReached { .. } | Self::LoopDetected)
96    }
97
98    pub fn description(&self) -> String {
99        match self {
100            Self::Success => "Task completed successfully".into(),
101            Self::StoppedNoAction => "Stopped after agent signaled no further actions".into(),
102            Self::TurnLimitReached { max_turns, actual_turns } => {
103                format!("Stopped after reaching turn limit (max: {max_turns}, reached: {actual_turns})")
104            }
105            Self::BudgetLimitReached { max_budget_usd, actual_cost_usd } => {
106                format!("Stopped after reaching budget limit (max: ${max_budget_usd:.4}, spent: ${actual_cost_usd:.4})")
107            }
108            Self::ToolLoopLimitReached { max_tool_loops, actual_tool_loops } => {
109                if *max_tool_loops == 0 {
110                    "Stopped after a tool safeguard halted execution".into()
111                } else {
112                    format!(
113                        "Stopped after reaching tool loop limit (max: {max_tool_loops}, reached: {actual_tool_loops})"
114                    )
115                }
116            }
117            Self::LoopDetected => "Stopped due to infinite loop detection".into(),
118            Self::Cancelled => "Task cancelled by user".into(),
119            Self::HandedOff { target } => format!("Task handed off to `{target}`"),
120            Self::Escalated { reason, tool_name } => {
121                format!("Task escalated: {tool_name} — {reason}")
122            }
123            Self::Refused { reason } => reason.clone(),
124            Self::Failed { reason, accomplished, recovery_suggestion, .. } => {
125                let mut parts = vec![format!("Task failed: {reason}")];
126                if !accomplished.is_empty() {
127                    parts.push(format!("Accomplished: {}", accomplished.join(", ")));
128                }
129                if let Some(suggestion) = recovery_suggestion {
130                    parts.push(format!("Suggestion: {suggestion}"));
131                }
132                parts.join("\n")
133            }
134            Self::Unknown => "Task outcome could not be determined".into(),
135        }
136    }
137
138    pub fn code(&self) -> &'static str {
139        match self {
140            Self::Success => "success",
141            Self::StoppedNoAction => "stopped_no_action",
142            Self::TurnLimitReached { .. } => "turn_limit_reached",
143            Self::BudgetLimitReached { .. } => "budget_limit_reached",
144            Self::ToolLoopLimitReached { .. } => "tool_loop_limit_reached",
145            Self::LoopDetected => "loop_detected",
146            Self::Cancelled => "cancelled",
147            Self::HandedOff { .. } => "handed_off",
148            Self::Escalated { .. } => "escalated",
149            Self::Refused { .. } => "refused",
150            Self::Failed { .. } => "failed",
151            Self::Unknown => "unknown",
152        }
153    }
154
155    pub fn thread_completion_subtype(&self) -> ThreadCompletionSubtype {
156        match self {
157            Self::Success | Self::StoppedNoAction => ThreadCompletionSubtype::Success,
158            Self::TurnLimitReached { .. } => ThreadCompletionSubtype::ErrorMaxTurns,
159            Self::BudgetLimitReached { .. } => ThreadCompletionSubtype::ErrorMaxBudgetUsd,
160            Self::Cancelled => ThreadCompletionSubtype::Cancelled,
161            Self::ToolLoopLimitReached { .. }
162            | Self::LoopDetected
163            | Self::HandedOff { .. }
164            | Self::Escalated { .. }
165            | Self::Refused { .. }
166            | Self::Failed { .. }
167            | Self::Unknown => ThreadCompletionSubtype::ErrorDuringExecution,
168        }
169    }
170
171    pub fn success() -> Self {
172        Self::Success
173    }
174
175    pub fn turn_limit_reached(max_turns: usize, actual_turns: usize) -> Self {
176        Self::TurnLimitReached { max_turns, actual_turns }
177    }
178
179    pub fn budget_limit_reached(max_budget_usd: f64, actual_cost_usd: f64) -> Self {
180        Self::BudgetLimitReached { max_budget_usd, actual_cost_usd }
181    }
182
183    /// Safeguard halt from a rate-limited tool (not the removed configured
184    /// budget): reuses the legacy loop-limit outcome with `max_tool_loops: 0`
185    /// so existing consumers keep one "tool safeguard stopped the run" shape.
186    pub fn tool_safeguard_halt(actual_tool_loops: usize) -> Self {
187        Self::ToolLoopLimitReached { max_tool_loops: 0, actual_tool_loops }
188    }
189
190    pub fn failed(
191        reason: String,
192        accomplished: Vec<String>,
193        recovery_suggestion: Option<String>,
194        checkpoint_path: Option<String>,
195    ) -> Self {
196        Self::Failed {
197            reason,
198            accomplished,
199            recovery_suggestion,
200            checkpoint_path,
201        }
202    }
203
204    pub fn escalated(reason: String, tool_name: String) -> Self {
205        Self::Escalated { reason, tool_name }
206    }
207
208    pub fn refused(reason: String) -> Self {
209        Self::Refused { reason }
210    }
211
212    pub fn handed_off(target: String) -> Self {
213        Self::HandedOff { target }
214    }
215}
216
217impl fmt::Display for TaskOutcome {
218    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
219        f.write_str(self.code())
220    }
221}
222
223#[cfg(test)]
224mod tests {
225    use super::{TaskOutcome, ThreadCompletionSubtype};
226
227    #[test]
228    fn tool_safeguard_halt_renders_without_a_budget_count() {
229        let outcome = TaskOutcome::tool_safeguard_halt(0);
230
231        assert!(outcome.is_hard_block());
232        assert_eq!(outcome.code(), "tool_loop_limit_reached");
233        assert_eq!(outcome.description(), "Stopped after a tool safeguard halted execution");
234    }
235
236    #[test]
237    fn thread_completion_subtype_matches_public_result_states() {
238        assert_eq!(TaskOutcome::Success.thread_completion_subtype(), ThreadCompletionSubtype::Success);
239        assert_eq!(TaskOutcome::StoppedNoAction.thread_completion_subtype(), ThreadCompletionSubtype::Success);
240        assert_eq!(
241            TaskOutcome::turn_limit_reached(3, 3).thread_completion_subtype(),
242            ThreadCompletionSubtype::ErrorMaxTurns
243        );
244        assert_eq!(
245            TaskOutcome::budget_limit_reached(1.0, 1.2).thread_completion_subtype(),
246            ThreadCompletionSubtype::ErrorMaxBudgetUsd
247        );
248        assert_eq!(TaskOutcome::Cancelled.thread_completion_subtype(), ThreadCompletionSubtype::Cancelled);
249        assert_eq!(
250            (TaskOutcome::failed("boom".to_string(), vec![], None, None)).thread_completion_subtype(),
251            ThreadCompletionSubtype::ErrorDuringExecution
252        );
253        assert_eq!(
254            TaskOutcome::refused("declined".to_string()).thread_completion_subtype(),
255            ThreadCompletionSubtype::ErrorDuringExecution
256        );
257    }
258
259    #[test]
260    fn refused_outcome_is_a_distinct_failure_that_carries_the_reason() {
261        let outcome = TaskOutcome::refused("The model declined this request.".to_string());
262
263        assert!(!outcome.is_success());
264        assert!(!outcome.is_hard_block());
265        assert_eq!(outcome.code(), "refused");
266        assert_eq!(outcome.description(), "The model declined this request.");
267
268        let json = serde_json::to_value(&outcome).expect("serialize refused outcome");
269        assert_eq!(json, serde_json::json!({"refused": {"reason": "The model declined this request."}}));
270        let round_trip: TaskOutcome = serde_json::from_value(json).expect("deserialize refused outcome");
271        assert_eq!(round_trip, outcome);
272    }
273}
274
275/// Aggregated results returned by the autonomous agent runner.
276#[derive(Debug, Clone, Serialize, Deserialize)]
277pub struct TaskResults {
278    /// Identifiers of any contexts created during execution.
279    #[serde(default)]
280    pub created_contexts: Vec<String>,
281    /// File paths modified during the task.
282    #[serde(default)]
283    pub modified_files: Vec<String>,
284    /// Terminal commands executed while solving the task.
285    #[serde(default)]
286    pub executed_commands: Vec<String>,
287    /// Natural-language summary of the run assembled by the agent.
288    pub summary: String,
289    /// Provider stop reason associated with the last model turn, when available.
290    #[serde(default, skip_serializing_if = "Option::is_none")]
291    pub stop_reason: Option<String>,
292    /// Estimated total API cost in USD, when pricing metadata is available.
293    #[serde(default, skip_serializing_if = "Option::is_none")]
294    pub total_cost_usd: Option<f64>,
295    /// Collected warnings emitted while processing the task.
296    #[serde(default)]
297    pub warnings: Vec<String>,
298    /// Structured execution timeline for headless modes.
299    #[serde(default)]
300    pub thread_events: Vec<ThreadEvent>,
301    /// Finalized outcome of the task.
302    pub outcome: TaskOutcome,
303    /// Number of autonomous turns executed.
304    pub turns_executed: usize,
305    /// Total runtime in milliseconds.
306    pub total_duration_ms: u128,
307    /// Average turn duration in milliseconds (if turns executed).
308    #[serde(default)]
309    pub average_turn_duration_ms: Option<f64>,
310    /// Longest individual turn duration in milliseconds.
311    #[serde(default)]
312    pub max_turn_duration_ms: Option<u128>,
313    /// Per-turn duration metrics in milliseconds.
314    #[serde(default)]
315    pub turn_durations_ms: Vec<u128>,
316}