Skip to main content

vtcode_exec_events/
items.rs

1//! Timeline item payloads carried by thread item events.
2use serde::{Deserialize, Serialize};
3use serde_json::Value;
4
5use super::{Diagnostic, ErrorItem, HarnessEventItem, ItemContext};
6
7#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
8#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
9pub struct ThreadItem {
10    #[serde(default, skip_serializing_if = "Option::is_none")]
11    pub context: Option<Box<ItemContext>>,
12    /// Stable identifier associated with the item.
13    pub id: String,
14    /// Embedded event details for the item type.
15    #[serde(flatten)]
16    pub details: ThreadItemDetails,
17}
18
19#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
20#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
21#[serde(tag = "type", rename_all = "snake_case")]
22pub enum ThreadItemDetails {
23    /// Message authored by the agent.
24    AgentMessage(AgentMessageItem),
25    /// Structured plan content authored by the agent in Planning workflow.
26    Plan(PlanItem),
27    /// Free-form reasoning text produced during a turn.
28    Reasoning(Box<ReasoningItem>),
29    /// Public rationale explicitly recorded by the agent; never private reasoning.
30    Decision(Box<DecisionItem>),
31    /// Command execution lifecycle update for an actual shell/PTY process.
32    CommandExecution(Box<CommandExecutionItem>),
33    /// Tool invocation lifecycle update.
34    ToolInvocation(Box<ToolInvocationItem>),
35    /// Tool output lifecycle update tied to a tool invocation.
36    ToolOutput(Box<ToolOutputItem>),
37    /// File change summary associated with the turn.
38    FileChange(Box<FileChangeItem>),
39    /// MCP tool invocation status.
40    McpToolCall(Box<McpToolCallItem>),
41    /// Web search event emitted by a registered search provider.
42    WebSearch(Box<WebSearchItem>),
43    /// Harness-managed continuation or verification lifecycle event.
44    Harness(Box<HarnessEventItem>),
45    /// General error captured for auditing.
46    Error(ErrorItem),
47}
48
49#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
50#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
51pub struct AgentMessageItem {
52    /// Textual content of the agent message.
53    pub text: String,
54}
55
56/// A consequential choice and the agent's reported public rationale.
57#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
58#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
59pub struct DecisionItem {
60    pub summary: String,
61    pub rationale: String,
62    #[serde(default)]
63    pub alternatives: Vec<String>,
64    #[serde(default)]
65    pub evidence_ids: Vec<String>,
66}
67
68#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
69#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
70pub struct PlanItem {
71    /// Plan markdown content.
72    pub text: String,
73}
74
75#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
76#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
77pub struct ReasoningItem {
78    /// Operational diagnostic independent of private model reasoning.
79    #[serde(default, skip_serializing_if = "Option::is_none")]
80    pub diagnostic: Option<Box<Diagnostic>>,
81    /// Free-form reasoning content captured during planning.
82    pub text: String,
83    /// Optional stage of reasoning (e.g., "analysis", "plan", "verification",
84    /// or the bounded evidence-only "diagnosis" stage).
85    #[serde(skip_serializing_if = "Option::is_none")]
86    pub stage: Option<String>,
87}
88
89#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
90#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
91#[serde(rename_all = "snake_case")]
92pub enum CommandExecutionStatus {
93    /// Command finished successfully.
94    #[default]
95    Completed,
96    /// Command failed (non-zero exit code or runtime error).
97    Failed,
98    /// Command is still running and may emit additional output.
99    InProgress,
100}
101
102impl CommandExecutionStatus {
103    /// Wire spelling (`snake_case`, matching `serde(rename_all)`).
104    pub const fn as_str(&self) -> &'static str {
105        match self {
106            Self::Completed => "completed",
107            Self::Failed => "failed",
108            Self::InProgress => "in_progress",
109        }
110    }
111}
112
113#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
114#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
115pub struct CommandExecutionItem {
116    /// Tool or command identifier executed by the runner.
117    pub command: String,
118    /// Arguments passed to the tool invocation, when available.
119    #[serde(skip_serializing_if = "Option::is_none")]
120    pub arguments: Option<Value>,
121    /// Aggregated output emitted by the command.
122    #[serde(default)]
123    pub aggregated_output: String,
124    /// Exit code reported by the process, when available.
125    #[serde(skip_serializing_if = "Option::is_none")]
126    pub exit_code: Option<i32>,
127    /// Current status of the command execution.
128    pub status: CommandExecutionStatus,
129}
130
131#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
132#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
133#[serde(rename_all = "snake_case")]
134pub enum ToolCallStatus {
135    /// Tool finished successfully.
136    #[default]
137    Completed,
138    /// Tool failed.
139    Failed,
140    /// Tool is still running and may emit additional output.
141    InProgress,
142}
143
144impl ToolCallStatus {
145    /// Wire spelling (`snake_case`, matching `serde(rename_all)`).
146    pub const fn as_str(&self) -> &'static str {
147        match self {
148            Self::Completed => "completed",
149            Self::Failed => "failed",
150            Self::InProgress => "in_progress",
151        }
152    }
153}
154
155/// Fine-grained outcome of a tool invocation lifecycle.
156///
157/// Mirrors the outcome taxonomy used by the runtime: `status` remains the
158/// coarse lifecycle signal (`Completed` / `Failed` / `InProgress`), while
159/// `outcome` captures *why* the invocation terminated. Consumers that only
160/// need success/failure can continue to read `status`; analytics and the UI
161/// layer use `outcome` for richer classification.
162#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
163#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
164#[serde(rename_all = "snake_case")]
165pub enum ToolOutcome {
166    /// Tool executed and returned a result.
167    #[default]
168    Success,
169    /// Tool executed but returned an error.
170    Error,
171    /// User rejected the permission prompt.
172    PermissionRejected,
173    /// User cancelled the permission prompt (e.g. Ctrl+C / Esc).
174    PermissionCancelled,
175    /// User provided a followup message instead of approving.
176    Followup,
177    /// A user-configured hook blocked execution.
178    HookDenied,
179    /// Tool not found or arguments couldn't be parsed.
180    InvalidTool,
181    /// Tool was cancelled during execution or closed before dispatch when its turn ended.
182    Cancelled,
183}
184
185impl ToolOutcome {
186    #[must_use]
187    pub const fn is_terminal(self) -> bool {
188        !matches!(self, Self::Followup)
189    }
190
191    /// Wire spelling (`snake_case`, matching `serde(rename_all)`).
192    #[must_use]
193    pub const fn as_str(self) -> &'static str {
194        match self {
195            Self::Success => "success",
196            Self::Error => "error",
197            Self::PermissionRejected => "permission_rejected",
198            Self::PermissionCancelled => "permission_cancelled",
199            Self::Followup => "followup",
200            Self::HookDenied => "hook_denied",
201            Self::InvalidTool => "invalid_tool",
202            Self::Cancelled => "cancelled",
203        }
204    }
205}
206
207/// Map a terminal [`ToolCallStatus`] to its corresponding [`ToolOutcome`].
208///
209/// # Panics
210///
211/// Panics if `status` is [`ToolCallStatus::InProgress`], which is a non-terminal
212/// state and must never be passed to a completion-event emitter.
213#[must_use]
214#[allow(
215    clippy::unreachable,
216    reason = "Intentional compatibility, platform, or test-only suppression."
217)]
218pub fn tool_outcome_from_status(status: &ToolCallStatus) -> ToolOutcome {
219    match status {
220        ToolCallStatus::Completed => ToolOutcome::Success,
221        ToolCallStatus::Failed => ToolOutcome::Error,
222        ToolCallStatus::InProgress => unreachable!("InProgress status passed to completion event"),
223    }
224}
225
226#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
227#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
228pub struct ToolInvocationItem {
229    /// Name of the invoked tool.
230    pub tool_name: String,
231    /// Structured arguments passed to the tool.
232    #[serde(skip_serializing_if = "Option::is_none")]
233    pub arguments: Option<Value>,
234    /// Raw model-emitted tool call identifier, when available.
235    #[serde(skip_serializing_if = "Option::is_none")]
236    pub tool_call_id: Option<String>,
237    /// Current lifecycle status of the invocation.
238    pub status: ToolCallStatus,
239    /// Fine-grained outcome of the invocation lifecycle.
240    #[serde(skip_serializing_if = "Option::is_none")]
241    pub outcome: Option<ToolOutcome>,
242}
243
244#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
245#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
246pub struct ToolOutputItem {
247    /// Identifier of the related harness invocation item.
248    pub call_id: String,
249    /// Raw model-emitted tool call identifier, when available.
250    #[serde(skip_serializing_if = "Option::is_none")]
251    pub tool_call_id: Option<String>,
252    /// Canonical spool file path when the full output was written to disk.
253    #[serde(skip_serializing_if = "Option::is_none")]
254    pub spool_path: Option<String>,
255    /// Output snapshot, or a chunk when `is_delta` is true.
256    #[serde(default)]
257    pub output: String,
258    /// Whether an updated item appends to the prior output. Absent means a
259    /// snapshot for compatibility with older event producers.
260    #[serde(default, skip_serializing_if = "Option::is_none")]
261    pub is_delta: Option<bool>,
262    /// Exit code reported by the tool, when available.
263    #[serde(skip_serializing_if = "Option::is_none")]
264    pub exit_code: Option<i32>,
265    /// Current lifecycle status of the output item.
266    pub status: ToolCallStatus,
267    /// MCP Apps referenced by this output, when the tool result was enriched
268    /// with app disclosure. Surfaces render preview affordances from these;
269    /// empty for non-app results. Schema 0.21.0; omitted when empty.
270    #[serde(default, skip_serializing_if = "Vec::is_empty")]
271    pub app_previews: Vec<AppPreviewItem>,
272}
273
274/// Disclosure facts about one MCP Apps resource referenced by a tool output.
275///
276/// Mirrors the disclosure attached at execution time; surfaces must not
277/// re-derive these by parsing rendered output text.
278#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
279#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
280pub struct AppPreviewItem {
281    /// Canonical `ui://` resource URI.
282    pub uri: String,
283    /// MIME type of the first content block, when the server provides one.
284    #[serde(default, skip_serializing_if = "Option::is_none")]
285    pub mime_type: Option<String>,
286    /// Total body bytes across content blocks.
287    #[serde(default)]
288    pub bytes: u64,
289    /// Number of content blocks.
290    #[serde(default)]
291    pub blocks: usize,
292    /// Declared UI sandbox posture, when the server declares `_meta.ui`.
293    #[serde(default, skip_serializing_if = "Option::is_none")]
294    pub ui: Option<AppUiPosture>,
295}
296
297/// Declared sandbox posture of an MCP Apps UI resource (SEP-1865 `UIResourceMeta`).
298#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
299#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
300pub struct AppUiPosture {
301    /// Origins for network requests (`csp.connectDomains`).
302    #[serde(default, skip_serializing_if = "Vec::is_empty")]
303    pub connect_domains: Vec<String>,
304    /// Origins for static resources (`csp.resourceDomains`).
305    #[serde(default, skip_serializing_if = "Vec::is_empty")]
306    pub resource_domains: Vec<String>,
307    /// Origins for nested iframes (`csp.frameDomains`).
308    #[serde(default, skip_serializing_if = "Vec::is_empty")]
309    pub frame_domains: Vec<String>,
310    /// Allowed base URIs (`csp.baseUriDomains`).
311    #[serde(default, skip_serializing_if = "Vec::is_empty")]
312    pub base_uri_domains: Vec<String>,
313    /// Requested permission-policy features (`permissions`).
314    #[serde(default, skip_serializing_if = "Vec::is_empty")]
315    pub permissions: Vec<String>,
316    /// Dedicated sandbox origin for the view (`domain`).
317    #[serde(default, skip_serializing_if = "Option::is_none")]
318    pub domain: Option<String>,
319}
320
321#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
322#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
323pub struct FileChangeItem {
324    /// Captured preview was truncated, suppressed, or unavailable.
325    #[serde(default, skip_serializing_if = "Option::is_none")]
326    pub diff_incomplete: Option<bool>,
327    /// List of individual file updates included in the change set.
328    pub changes: Vec<FileUpdateChange>,
329    /// Whether the patch application succeeded.
330    pub status: PatchApplyStatus,
331    /// Optional precomputed unified diff for the change set.
332    ///
333    /// Populated by the turn diff tracker so consumers can render per-change
334    /// previews without recomputation. Absent in older events.
335    #[serde(default, skip_serializing_if = "Option::is_none")]
336    pub unified_diff: Option<String>,
337    /// Optional added-line count for the change set.
338    #[serde(default, skip_serializing_if = "Option::is_none")]
339    pub additions: Option<u64>,
340    /// Optional deleted-line count for the change set.
341    #[serde(default, skip_serializing_if = "Option::is_none")]
342    pub deletions: Option<u64>,
343}
344
345#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
346#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
347pub struct FileUpdateChange {
348    /// Path of the file that was updated.
349    pub path: String,
350    /// Type of change applied to the file.
351    pub kind: PatchChangeKind,
352    /// Whether the recorded preview normalized line endings (a `\r` was
353    /// present, so the recorded bytes cannot reproduce the original
354    /// exactly). `None` means unknown (legacy events predating the flag).
355    #[serde(default, skip_serializing_if = "Option::is_none")]
356    pub terminators_normalized: Option<bool>,
357}
358
359#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
360#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
361#[serde(rename_all = "snake_case")]
362pub enum PatchApplyStatus {
363    /// Patch successfully applied.
364    Completed,
365    /// Patch application failed.
366    Failed,
367}
368
369impl PatchApplyStatus {
370    /// Wire spelling (`snake_case`, matching `serde(rename_all)`).
371    pub const fn as_str(&self) -> &'static str {
372        match self {
373            Self::Completed => "completed",
374            Self::Failed => "failed",
375        }
376    }
377}
378
379#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
380#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
381#[serde(rename_all = "snake_case")]
382pub enum PatchChangeKind {
383    /// File addition.
384    Add,
385    /// File deletion.
386    Delete,
387    /// File update in place.
388    Update,
389}
390
391#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
392#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
393pub struct McpToolCallItem {
394    /// Name of the MCP tool invoked by the agent.
395    pub tool_name: String,
396    /// Arguments passed to the tool invocation, if any.
397    #[serde(skip_serializing_if = "Option::is_none")]
398    pub arguments: Option<Value>,
399    /// Result payload returned by the tool, if captured.
400    #[serde(skip_serializing_if = "Option::is_none")]
401    pub result: Option<String>,
402    /// Lifecycle status for the tool call.
403    #[serde(skip_serializing_if = "Option::is_none")]
404    pub status: Option<McpToolCallStatus>,
405}
406
407#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
408#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
409#[serde(rename_all = "snake_case")]
410pub enum McpToolCallStatus {
411    /// Tool invocation has started.
412    Started,
413    /// Tool invocation completed successfully.
414    Completed,
415    /// Tool invocation failed.
416    Failed,
417}
418
419impl McpToolCallStatus {
420    /// Wire spelling (`snake_case`, matching `serde(rename_all)`).
421    pub const fn as_str(&self) -> &'static str {
422        match self {
423            Self::Started => "started",
424            Self::Completed => "completed",
425            Self::Failed => "failed",
426        }
427    }
428}
429
430#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
431#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
432pub struct WebSearchItem {
433    /// Query that triggered the search.
434    pub query: String,
435    /// Search provider identifier, when known.
436    #[serde(skip_serializing_if = "Option::is_none")]
437    pub provider: Option<String>,
438    /// Optional raw search results captured for auditing.
439    #[serde(skip_serializing_if = "Option::is_none")]
440    pub results: Option<Vec<String>>,
441}