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 resource URI: `ui://` for MCP app bodies, `computer-preview://`
282    /// for ephemeral computer-use screenshots (memory-only, expire on eviction).
283    pub uri: String,
284    /// MIME type of the first content block, when the server provides one.
285    #[serde(default, skip_serializing_if = "Option::is_none")]
286    pub mime_type: Option<String>,
287    /// Total body bytes across content blocks.
288    #[serde(default)]
289    pub bytes: u64,
290    /// Number of content blocks.
291    #[serde(default)]
292    pub blocks: usize,
293    /// Declared UI sandbox posture, when the server declares `_meta.ui`.
294    #[serde(default, skip_serializing_if = "Option::is_none")]
295    pub ui: Option<AppUiPosture>,
296}
297
298/// Declared sandbox posture of an MCP Apps UI resource (SEP-1865 `UIResourceMeta`).
299#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
300#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
301pub struct AppUiPosture {
302    /// Origins for network requests (`csp.connectDomains`).
303    #[serde(default, skip_serializing_if = "Vec::is_empty")]
304    pub connect_domains: Vec<String>,
305    /// Origins for static resources (`csp.resourceDomains`).
306    #[serde(default, skip_serializing_if = "Vec::is_empty")]
307    pub resource_domains: Vec<String>,
308    /// Origins for nested iframes (`csp.frameDomains`).
309    #[serde(default, skip_serializing_if = "Vec::is_empty")]
310    pub frame_domains: Vec<String>,
311    /// Allowed base URIs (`csp.baseUriDomains`).
312    #[serde(default, skip_serializing_if = "Vec::is_empty")]
313    pub base_uri_domains: Vec<String>,
314    /// Requested permission-policy features (`permissions`).
315    #[serde(default, skip_serializing_if = "Vec::is_empty")]
316    pub permissions: Vec<String>,
317    /// Dedicated sandbox origin for the view (`domain`).
318    #[serde(default, skip_serializing_if = "Option::is_none")]
319    pub domain: Option<String>,
320}
321
322#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
323#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
324pub struct FileChangeItem {
325    /// Captured preview was truncated, suppressed, or unavailable.
326    #[serde(default, skip_serializing_if = "Option::is_none")]
327    pub diff_incomplete: Option<bool>,
328    /// List of individual file updates included in the change set.
329    pub changes: Vec<FileUpdateChange>,
330    /// Whether the patch application succeeded.
331    pub status: PatchApplyStatus,
332    /// Optional precomputed unified diff for the change set.
333    ///
334    /// Populated by the turn diff tracker so consumers can render per-change
335    /// previews without recomputation. Absent in older events.
336    #[serde(default, skip_serializing_if = "Option::is_none")]
337    pub unified_diff: Option<String>,
338    /// Optional added-line count for the change set.
339    #[serde(default, skip_serializing_if = "Option::is_none")]
340    pub additions: Option<u64>,
341    /// Optional deleted-line count for the change set.
342    #[serde(default, skip_serializing_if = "Option::is_none")]
343    pub deletions: Option<u64>,
344}
345
346#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
347#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
348pub struct FileUpdateChange {
349    /// Path of the file that was updated.
350    pub path: String,
351    /// Type of change applied to the file.
352    pub kind: PatchChangeKind,
353    /// Whether the recorded preview normalized line endings (a `\r` was
354    /// present, so the recorded bytes cannot reproduce the original
355    /// exactly). `None` means unknown (legacy events predating the flag).
356    #[serde(default, skip_serializing_if = "Option::is_none")]
357    pub terminators_normalized: Option<bool>,
358}
359
360#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
361#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
362#[serde(rename_all = "snake_case")]
363pub enum PatchApplyStatus {
364    /// Patch successfully applied.
365    Completed,
366    /// Patch application failed.
367    Failed,
368}
369
370impl PatchApplyStatus {
371    /// Wire spelling (`snake_case`, matching `serde(rename_all)`).
372    pub const fn as_str(&self) -> &'static str {
373        match self {
374            Self::Completed => "completed",
375            Self::Failed => "failed",
376        }
377    }
378}
379
380#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
381#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
382#[serde(rename_all = "snake_case")]
383pub enum PatchChangeKind {
384    /// File addition.
385    Add,
386    /// File deletion.
387    Delete,
388    /// File update in place.
389    Update,
390}
391
392#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
393#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
394pub struct McpToolCallItem {
395    /// Name of the MCP tool invoked by the agent.
396    pub tool_name: String,
397    /// Arguments passed to the tool invocation, if any.
398    #[serde(skip_serializing_if = "Option::is_none")]
399    pub arguments: Option<Value>,
400    /// Result payload returned by the tool, if captured.
401    #[serde(skip_serializing_if = "Option::is_none")]
402    pub result: Option<String>,
403    /// Lifecycle status for the tool call.
404    #[serde(skip_serializing_if = "Option::is_none")]
405    pub status: Option<McpToolCallStatus>,
406}
407
408#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
409#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
410#[serde(rename_all = "snake_case")]
411pub enum McpToolCallStatus {
412    /// Tool invocation has started.
413    Started,
414    /// Tool invocation completed successfully.
415    Completed,
416    /// Tool invocation failed.
417    Failed,
418}
419
420impl McpToolCallStatus {
421    /// Wire spelling (`snake_case`, matching `serde(rename_all)`).
422    pub const fn as_str(&self) -> &'static str {
423        match self {
424            Self::Started => "started",
425            Self::Completed => "completed",
426            Self::Failed => "failed",
427        }
428    }
429}
430
431#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
432#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
433pub struct WebSearchItem {
434    /// Query that triggered the search.
435    pub query: String,
436    /// Search provider identifier, when known.
437    #[serde(skip_serializing_if = "Option::is_none")]
438    pub provider: Option<String>,
439    /// Optional raw search results captured for auditing.
440    #[serde(skip_serializing_if = "Option::is_none")]
441    pub results: Option<Vec<String>>,
442}