Skip to main content

vtcode_exec_events/
lib.rs

1#![allow(
2    missing_docs,
3    dead_code,
4    unused_imports,
5    reason = "Intentional compatibility, platform, or test-only suppression."
6)]
7//! Structured execution telemetry events shared across VT Code crates.
8//!
9//! This crate exposes the serialized schema for thread lifecycle updates,
10//! command execution results, and other timeline artifacts emitted by the
11//! automation runtime. Downstream applications can deserialize these
12//! structures to drive dashboards, logging, or auditing pipelines without
13//! depending on the full `vtcode-core` crate.
14//!
15//! # Agent Trace Support
16//!
17//! This crate implements the [Agent Trace](https://agent-trace.dev/) specification
18//! for tracking AI-generated code attribution. See the [`trace`] module for details.
19
20use serde::{Deserialize, Serialize};
21
22pub mod atif;
23pub mod diagnostic;
24pub use diagnostic::{Diagnostic, DiagnosticAction, DiagnosticSeverity};
25pub mod goal;
26pub mod items;
27pub use items::{
28    AgentMessageItem, AppPreviewItem, AppUiPosture, CommandExecutionItem, CommandExecutionStatus, DecisionItem,
29    FileChangeItem, FileUpdateChange, McpToolCallItem, McpToolCallStatus, PatchApplyStatus, PatchChangeKind, PlanItem,
30    ReasoningItem, ThreadItem, ThreadItemDetails, ToolCallStatus, ToolInvocationItem, ToolOutcome, ToolOutputItem,
31    WebSearchItem, tool_outcome_from_status,
32};
33pub mod matrix;
34pub mod planning;
35pub mod trace;
36pub mod tracker;
37
38/// Semantic version of the serialized event schema exported by this crate.
39pub const EVENT_SCHEMA_VERSION: &str = "0.29.0";
40
41/// Wraps a [`ThreadEvent`] with schema metadata so downstream consumers can
42/// negotiate compatibility before processing an event stream.
43#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
44#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
45pub struct VersionedThreadEvent {
46    /// Semantic version describing the schema of the nested event payload.
47    schema_version: String,
48    /// Concrete event emitted by the agent runtime.
49    event: ThreadEvent,
50}
51
52impl VersionedThreadEvent {
53    /// Creates a new [`VersionedThreadEvent`] using the current
54    /// [`EVENT_SCHEMA_VERSION`].
55    pub fn new(event: ThreadEvent) -> Self {
56        Self {
57            schema_version: EVENT_SCHEMA_VERSION.to_string(),
58            event,
59        }
60    }
61
62    /// Returns the nested [`ThreadEvent`] by reference.
63    pub fn event(&self) -> &ThreadEvent {
64        &self.event
65    }
66
67    /// Returns the nested [`ThreadEvent`], consuming the wrapper.
68    pub fn into_event(self) -> ThreadEvent {
69        self.event
70    }
71}
72
73impl From<ThreadEvent> for VersionedThreadEvent {
74    fn from(event: ThreadEvent) -> Self {
75        Self::new(event)
76    }
77}
78
79/// Sink for processing [`ThreadEvent`] instances.
80pub trait EventEmitter {
81    /// Invoked for each event emitted by the automation runtime.
82    fn emit(&mut self, event: &ThreadEvent);
83}
84
85impl<F> EventEmitter for F
86where
87    F: FnMut(&ThreadEvent),
88{
89    fn emit(&mut self, event: &ThreadEvent) {
90        self(event);
91    }
92}
93
94#[cfg(feature = "serde-json")]
95pub mod json;
96
97#[cfg(feature = "telemetry-log")]
98mod log_support;
99
100#[cfg(feature = "telemetry-log")]
101pub use log_support::PublicLogEmitter as LogEmitter;
102
103#[cfg(feature = "telemetry-tracing")]
104mod tracing_support;
105
106#[cfg(feature = "telemetry-tracing")]
107pub use tracing_support::PublicTracingEmitter as TracingEmitter;
108
109#[cfg(feature = "telemetry-otel")]
110mod otel_support;
111
112#[cfg(feature = "telemetry-otel")]
113pub use otel_support::PublicOtelEmitter as OtelEmitter;
114
115#[cfg(feature = "schema-export")]
116pub mod schema;
117
118/// Structured events emitted during autonomous execution.
119#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
120#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
121#[serde(tag = "type")]
122pub enum ThreadEvent {
123    /// Replayable local matrix lifecycle checkpoint.
124    #[serde(rename = "matrix.updated")]
125    MatrixUpdated(Box<matrix::MatrixSnapshot>),
126    /// Bounded task-tracker checklist snapshot after a mutation.
127    #[serde(rename = "tracker.updated")]
128    TrackerUpdated(Box<tracker::TrackerSnapshot>),
129    /// Bounded thread-goal snapshot after a mutation (`None` signals a clear).
130    #[serde(rename = "goal.updated")]
131    GoalUpdated(Box<goal::GoalUpdatedEvent>),
132    /// Indicates that a new execution thread has started.
133    #[serde(rename = "thread.started")]
134    ThreadStarted(ThreadStartedEvent),
135    /// Indicates that an execution thread has reached a terminal outcome.
136    #[serde(rename = "thread.completed")]
137    ThreadCompleted(Box<ThreadCompletedEvent>),
138    /// Indicates that conversation compaction replaced older history with a boundary.
139    #[serde(rename = "thread.compact_boundary")]
140    ThreadCompactBoundary(Box<ThreadCompactBoundaryEvent>),
141    /// Indicates that the approved plan handoff rebuilt a fresh execution context.
142    #[serde(rename = "context.reset")]
143    ContextReset(ContextResetEvent),
144    /// Marks the beginning of an execution turn.
145    #[serde(rename = "turn.started")]
146    TurnStarted(TurnStartedEvent),
147    /// Marks the completion of an execution turn.
148    #[serde(rename = "turn.completed")]
149    TurnCompleted(TurnCompletedEvent),
150    /// Marks a turn as failed with additional context.
151    #[serde(rename = "turn.failed")]
152    TurnFailed(TurnFailedEvent),
153    /// Marks a turn as blocked before success could be confirmed. Emitted
154    /// alongside `turn.failed` so UI subscribers get a first-class signal
155    /// with the fuse counters and last tool instead of inferring it.
156    #[serde(rename = "turn.blocked")]
157    TurnBlocked(Box<TurnBlockedEvent>),
158    /// Indicates that an item has started processing.
159    #[serde(rename = "item.started")]
160    ItemStarted(ItemStartedEvent),
161    /// Indicates that an item has been updated.
162    #[serde(rename = "item.updated")]
163    ItemUpdated(ItemUpdatedEvent),
164    /// Indicates that an item reached a terminal state.
165    #[serde(rename = "item.completed")]
166    ItemCompleted(ItemCompletedEvent),
167    /// Emitted when an MCP server offers app UI that the `off` apps tier
168    /// refuses. No `ui://` resource was fetched and no app rows render; the
169    /// refused URIs are listed so the denial stays visible.
170    #[serde(rename = "app.sandbox_denied")]
171    AppSandboxDenied(Box<AppSandboxDeniedEvent>),
172    /// Emitted when a tool requires user permission before execution.
173    #[serde(rename = "permission.requested")]
174    PermissionRequested(PermissionRequestedEvent),
175    /// Emitted when the user resolves a permission prompt.
176    #[serde(rename = "permission.resolved")]
177    PermissionResolved(PermissionResolvedEvent),
178    /// A mid-turn user interjection was merged into the running turn.
179    #[serde(rename = "interjected")]
180    Interjected(InterjectedEvent),
181    /// Streaming delta for a plan item in Planning workflow.
182    #[serde(rename = "plan.delta")]
183    PlanDelta(Box<PlanDeltaEvent>),
184    /// Indicates that a completed plan is waiting for an implementation decision.
185    #[serde(rename = "plan.approval.requested")]
186    PlanApprovalRequested(PlanApprovalRequestedEvent),
187    /// Records the user's or policy's decision about a completed plan.
188    #[serde(rename = "plan.approval.resolved")]
189    PlanApprovalResolved(PlanApprovalResolvedEvent),
190    /// Represents a fatal error.
191    #[serde(rename = "error")]
192    Error(ThreadErrorEvent),
193    /// Catch-all for unknown event types added in newer schema versions.
194    /// Preserves forward compatibility when older binaries read newer event streams.
195    #[serde(other)]
196    Unknown,
197}
198
199#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
200#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
201pub struct ThreadStartedEvent {
202    /// Unique identifier for the thread that was started.
203    pub thread_id: String,
204}
205
206#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
207#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
208#[serde(rename_all = "snake_case")]
209pub enum ThreadCompletionSubtype {
210    Success,
211    ErrorMaxTurns,
212    ErrorMaxBudgetUsd,
213    ErrorDuringExecution,
214    Cancelled,
215    /// Catch-all for unknown completion subtypes added in newer schema versions.
216    #[serde(other)]
217    Unknown,
218}
219
220impl ThreadCompletionSubtype {
221    pub const fn as_str(&self) -> &'static str {
222        match self {
223            Self::Success => "success",
224            Self::ErrorMaxTurns => "error_max_turns",
225            Self::ErrorMaxBudgetUsd => "error_max_budget_usd",
226            Self::ErrorDuringExecution => "error_during_execution",
227            Self::Cancelled => "cancelled",
228            Self::Unknown => "unknown",
229        }
230    }
231
232    pub const fn is_success(self) -> bool {
233        matches!(self, Self::Success)
234    }
235}
236
237#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
238#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
239#[serde(rename_all = "snake_case")]
240pub enum CompactionTrigger {
241    Manual,
242    Auto,
243    Recovery,
244    /// Compaction triggered by a mid-session switch of the main model or
245    /// provider, so the newly selected model starts from a clean summary.
246    ModelSwitch,
247    /// Catch-all for unknown triggers added in newer schema versions.
248    #[serde(other)]
249    Unknown,
250}
251
252impl CompactionTrigger {
253    pub const fn as_str(self) -> &'static str {
254        match self {
255            Self::Manual => "manual",
256            Self::Auto => "auto",
257            Self::Recovery => "recovery",
258            Self::ModelSwitch => "model_switch",
259            Self::Unknown => "unknown",
260        }
261    }
262}
263
264#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
265#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
266#[serde(rename_all = "snake_case")]
267pub enum CompactionMode {
268    Provider,
269    Local,
270    /// Catch-all for unknown modes added in newer schema versions.
271    #[serde(other)]
272    Unknown,
273}
274
275impl CompactionMode {
276    pub const fn as_str(self) -> &'static str {
277        match self {
278            Self::Provider => "provider",
279            Self::Local => "local",
280            Self::Unknown => "unknown",
281        }
282    }
283}
284
285#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
286#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
287pub struct ThreadCompletedEvent {
288    /// Runtime completion timestamp, absent from legacy events.
289    #[serde(default, skip_serializing_if = "Option::is_none")]
290    pub completed_at: Option<String>,
291    /// Stable thread identifier for the session.
292    pub thread_id: String,
293    /// Stable session identifier for the runtime that produced the thread.
294    pub session_id: String,
295    /// Coarse result category aligned with SDK-style terminal states.
296    pub subtype: ThreadCompletionSubtype,
297    /// VT Code-specific detailed outcome code.
298    pub outcome_code: String,
299    /// Final assistant result text when the thread completed successfully.
300    #[serde(skip_serializing_if = "Option::is_none")]
301    pub result: Option<String>,
302    /// Provider stop reason or VT Code terminal reason when available.
303    #[serde(skip_serializing_if = "Option::is_none")]
304    pub stop_reason: Option<String>,
305    /// Aggregated token usage across the thread.
306    pub usage: Usage,
307    /// Optional estimated total API cost for the thread.
308    #[serde(skip_serializing_if = "Option::is_none")]
309    pub total_cost_usd: Option<serde_json::Number>,
310    /// Number of turns executed before completion.
311    pub num_turns: usize,
312}
313
314#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
315#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
316pub struct ThreadCompactBoundaryEvent {
317    /// Stable thread identifier for the session.
318    pub thread_id: String,
319    /// Whether compaction was triggered manually or automatically.
320    pub trigger: CompactionTrigger,
321    /// Whether the compaction boundary came from provider-native or local compaction.
322    pub mode: CompactionMode,
323    /// Number of messages before compaction.
324    pub original_message_count: usize,
325    /// Number of messages after compaction.
326    pub compacted_message_count: usize,
327    /// Optional persisted artifact containing the archived compaction summary/history.
328    #[serde(skip_serializing_if = "Option::is_none")]
329    pub history_artifact_path: Option<String>,
330    /// Segment identifier that contained the request prefix before compaction.
331    #[serde(skip_serializing_if = "Option::is_none")]
332    pub previous_segment_id: Option<String>,
333    /// Segment identifier created after compaction.
334    #[serde(skip_serializing_if = "Option::is_none")]
335    pub new_segment_id: Option<String>,
336    /// Hash of the immutable request prefix before compaction.
337    #[serde(skip_serializing_if = "Option::is_none")]
338    pub previous_prefix_hash: Option<String>,
339    /// Hash of the immutable request prefix after compaction.
340    #[serde(skip_serializing_if = "Option::is_none")]
341    pub new_prefix_hash: Option<String>,
342    /// Hash of the ordered tool catalog before compaction.
343    #[serde(skip_serializing_if = "Option::is_none")]
344    pub previous_catalog_hash: Option<String>,
345    /// Hash of the ordered tool catalog after compaction.
346    #[serde(skip_serializing_if = "Option::is_none")]
347    pub new_catalog_hash: Option<String>,
348}
349
350#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
351#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
352#[serde(rename_all = "snake_case")]
353pub enum ContextResetTrigger {
354    /// The user selected the fresh-context plan approval path.
355    PlanApproval,
356    /// Catch-all for triggers introduced by newer schema versions.
357    #[serde(other)]
358    Unknown,
359}
360
361#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
362#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
363pub struct ContextResetEvent {
364    /// Stable thread identifier for the session.
365    pub thread_id: String,
366    /// Identifier of the turn that approved the plan.
367    pub turn_id: String,
368    /// What initiated the context reset.
369    pub trigger: ContextResetTrigger,
370    /// Whether the approved plan and task tracker survived the reset.
371    pub plan_preserved: bool,
372    /// Context pressure reported before the reset, expressed as a percentage.
373    pub previous_context_usage_percent: u8,
374    /// Whether the per-turn and per-session tool budgets were reset.
375    pub tool_budget_reset: bool,
376}
377
378#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
379#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
380pub struct TurnStartedEvent {
381    /// Optional decomposition of the assembled first-request prefix so
382    /// downstream consumers can attribute token overhead without inventing
383    /// parallel event types.
384    #[serde(skip_serializing_if = "Option::is_none")]
385    token_breakdown: Option<Box<TokenBreakdown>>,
386    /// Task identity and public input recorded at the request boundary.
387    #[serde(default, skip_serializing_if = "Option::is_none")]
388    pub context: Option<Box<ExecutionContext>>,
389}
390
391impl TurnStartedEvent {
392    /// Recorded prefix token breakdown, absent when the producer did not capture it.
393    pub fn token_breakdown(&self) -> Option<&TokenBreakdown> {
394        self.token_breakdown.as_deref()
395    }
396}
397
398/// Origin of a turn's input; internal turns retain their parent task.
399#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
400#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
401#[serde(rename_all = "snake_case")]
402pub enum InputOrigin {
403    User,
404    Correction,
405    PlanApproval,
406    Continuation,
407    Retry,
408}
409
410/// Optional recorded execution ancestry. Absent fields are historical gaps.
411#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
412#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
413pub struct ExecutionContext {
414    pub task_id: String,
415    pub turn_id: String,
416    pub actor_id: String,
417    #[serde(default, skip_serializing_if = "Option::is_none")]
418    pub parent_actor_id: Option<String>,
419    pub origin: InputOrigin,
420    pub timestamp: String,
421    #[serde(default, skip_serializing_if = "Option::is_none")]
422    pub goal: Option<String>,
423}
424
425/// Recorded shell classification, supplied by the runtime's shared classifier.
426#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
427#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
428#[serde(rename_all = "snake_case")]
429pub enum CommandActivity {
430    Inspection,
431    Verification,
432    Mutation,
433}
434
435/// Item identity, timing, and command semantics for explanation consumers.
436#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
437#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
438pub struct ItemContext {
439    pub task_id: String,
440    pub turn_id: String,
441    pub actor_id: String,
442    #[serde(default, skip_serializing_if = "Option::is_none")]
443    pub parent_actor_id: Option<String>,
444    pub timestamp: String,
445    #[serde(default, skip_serializing_if = "Option::is_none")]
446    pub activity: Option<CommandActivity>,
447}
448
449/// Per-request token-budget breakdown for the assembled first-request prefix.
450#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
451#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
452pub struct TokenBreakdown {
453    /// System prompt text tokens.
454    system_prompt_tokens: u64,
455    /// On-wire tool schema tokens.
456    tool_schema_tokens: u64,
457    /// Instruction file tokens included in the prompt.
458    instruction_file_tokens: u64,
459    /// Message history text tokens.
460    message_history_tokens: u64,
461    /// Cache read tokens (served from prior turns).
462    cache_read_tokens: u64,
463    /// Cache write tokens (new cache entries created this turn).
464    cache_write_tokens: u64,
465    /// Tokens that missed cache (neither read nor written).
466    cache_miss_tokens: u64,
467    /// Subagent bootstrap tokens, if this turn spawned a child agent.
468    #[serde(skip_serializing_if = "Option::is_none")]
469    subagent_bootstrap_tokens: Option<u64>,
470}
471
472/// Bound on exec session ids recorded in one turn's `turn.completed` event.
473/// Mirrors `SnapshotTurnDiagnostics::in_progress_exec_sessions` (cap 4,
474/// newest first) so `ThreadEvent` and checkpoint diagnostics cannot drift.
475pub const MAX_IN_PROGRESS_EXEC_SESSIONS: usize = 4;
476
477#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
478#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
479pub struct TurnCompletedEvent {
480    /// Identity of the final agent message, when known.
481    #[serde(default, skip_serializing_if = "Option::is_none")]
482    pub final_response_item_id: Option<Box<String>>,
483    #[serde(default, skip_serializing_if = "Option::is_none")]
484    pub completed_at: Option<Box<String>>,
485    /// Token usage summary for the completed turn.
486    pub usage: Usage,
487    /// Exec sessions still running when the turn ended (bounded, newest
488    /// first). Empty when every command settled within the turn. Correlates
489    /// with the next turn's transient exec-session resume hint without
490    /// requiring session-id reconstruction.
491    #[serde(
492        default,
493        skip_serializing_if = "Vec::is_empty",
494        deserialize_with = "deserialize_null_as_default"
495    )]
496    pub in_progress_exec_sessions: Vec<String>,
497}
498
499#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
500#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
501pub struct TurnFailedEvent {
502    #[serde(default, skip_serializing_if = "Option::is_none")]
503    pub completed_at: Option<Box<String>>,
504    /// Human-readable explanation describing why the turn failed.
505    pub message: String,
506    /// Optional token usage that was consumed before the failure occurred.
507    #[serde(skip_serializing_if = "Option::is_none")]
508    pub usage: Option<Usage>,
509}
510
511#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
512#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
513pub struct TurnBlockedEvent {
514    /// Runtime terminal timestamp, absent from legacy events.
515    #[serde(default, skip_serializing_if = "Option::is_none")]
516    pub completed_at: Option<String>,
517    /// Human-readable explanation describing why the turn was blocked.
518    pub message: String,
519    /// Display label of the last blocked tool call, when known.
520    #[serde(skip_serializing_if = "Option::is_none")]
521    pub last_tool: Option<String>,
522    /// Consecutive blocked tool calls observed this turn.
523    #[serde(default)]
524    pub blocked_streak: usize,
525    /// Total blocked tool calls observed this turn.
526    #[serde(default)]
527    pub blocked_total: usize,
528    /// Consecutive cap that was enforced.
529    #[serde(default)]
530    pub consecutive_cap: usize,
531    /// Total cap that was enforced.
532    #[serde(default)]
533    pub total_cap: usize,
534    /// Whether the fuse tripped while a tool-free recovery pass was active.
535    #[serde(default)]
536    pub recovery_active: bool,
537    /// Optional token usage that was consumed before the block occurred.
538    #[serde(skip_serializing_if = "Option::is_none")]
539    pub usage: Option<Usage>,
540}
541
542#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
543#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
544pub struct ThreadErrorEvent {
545    /// Fatal error message associated with the thread.
546    pub message: String,
547}
548
549#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
550#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
551pub struct AppSandboxDeniedEvent {
552    /// Tool whose result offered the refused app UI.
553    pub tool: String,
554    /// Apps tier that refused the UI (`off`).
555    pub tier: String,
556    /// Refused `ui://` URIs, in first-seen order (capped at 4).
557    pub uris: Vec<String>,
558}
559
560#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
561#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
562pub struct Usage {
563    /// Number of prompt tokens processed during the turn.
564    #[serde(default, deserialize_with = "deserialize_null_as_default")]
565    pub input_tokens: u64,
566    /// Number of cached prompt tokens reused from previous turns.
567    #[serde(default, deserialize_with = "deserialize_null_as_default")]
568    pub cached_input_tokens: u64,
569    /// Number of cache-creation tokens charged during the turn.
570    #[serde(default, deserialize_with = "deserialize_null_as_default")]
571    pub cache_creation_tokens: u64,
572    /// Number of completion tokens generated by the model.
573    #[serde(default, deserialize_with = "deserialize_null_as_default")]
574    pub output_tokens: u64,
575}
576
577/// Serde helper that accepts explicit `null` as `T::default()` for
578/// backward-compatible checkpoint/diagnostics payloads. Pair with
579/// `#[serde(default, deserialize_with = "deserialize_null_as_default")]` so
580/// both missing and `null` fields degrade to the default instead of failing
581/// deserialization. Reused by downstream crates (e.g. `vtcode-core`
582/// snapshots) so the null-tolerance rule cannot drift between copies.
583pub fn deserialize_null_as_default<'de, D, T>(deserializer: D) -> Result<T, D::Error>
584where
585    D: serde::Deserializer<'de>,
586    T: Deserialize<'de> + Default,
587{
588    Ok(Option::<T>::deserialize(deserializer)?.unwrap_or_default())
589}
590
591impl Usage {
592    /// Number of input tokens billed at the full input rate: neither served
593    /// from cache nor written to it. `input_tokens` is the total prompt token
594    /// count (uncached + cached + cache-creation), so both cached and
595    /// cache-creation tokens are subtracted out here.
596    #[must_use]
597    fn uncached_input_tokens(&self) -> u64 {
598        self.input_tokens
599            .saturating_sub(self.cached_input_tokens)
600            .saturating_sub(self.cache_creation_tokens)
601    }
602
603    /// Cache hit rate as a fraction (0.0 to 1.0): cached input over total input.
604    /// Returns `None` when no input tokens were recorded.
605    #[must_use]
606    pub fn cache_hit_rate(&self) -> Option<f64> {
607        if self.input_tokens == 0 {
608            return None;
609        }
610        Some(self.cached_input_tokens as f64 / self.input_tokens as f64)
611    }
612
613    /// Human-readable summary of prompt cache efficiency.
614    #[must_use]
615    pub fn cache_summary(&self) -> String {
616        let total_input = self.input_tokens;
617        if total_input == 0 {
618            return "No input tokens recorded.".to_string();
619        }
620
621        let cached = self.cached_input_tokens;
622        let creation = self.cache_creation_tokens;
623        let uncached = self.uncached_input_tokens();
624        let rate = cached as f64 / total_input as f64 * 100.0;
625        format!(
626            "Cache: {cached} cached / {total_input} total input ({rate:.1}% hit rate), \
627             {creation} cache-creation, {uncached} uncached"
628        )
629    }
630
631    /// Accumulate another usage sample into this one.
632    pub fn add(&mut self, other: &Usage) {
633        self.input_tokens = self.input_tokens.saturating_add(other.input_tokens);
634        self.cached_input_tokens = self.cached_input_tokens.saturating_add(other.cached_input_tokens);
635        self.cache_creation_tokens = self.cache_creation_tokens.saturating_add(other.cache_creation_tokens);
636        self.output_tokens = self.output_tokens.saturating_add(other.output_tokens);
637    }
638}
639
640#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
641#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
642pub struct ItemCompletedEvent {
643    /// Snapshot of the thread item that completed.
644    pub item: ThreadItem,
645}
646
647#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
648#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
649pub struct ItemStartedEvent {
650    /// Snapshot of the thread item that began processing.
651    pub item: ThreadItem,
652}
653
654#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
655#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
656pub struct ItemUpdatedEvent {
657    /// Snapshot of the thread item after it was updated.
658    pub item: ThreadItem,
659}
660
661#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
662#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
663pub struct PlanDeltaEvent {
664    /// Identifier of the thread emitting this plan delta.
665    pub thread_id: String,
666    /// Identifier of the current turn.
667    pub turn_id: String,
668    /// Identifier of the plan item receiving the delta.
669    pub item_id: String,
670    /// Incremental plan text chunk.
671    pub delta: String,
672    /// Runtime-owned recovery checkpoint; absent in older sessions.
673    #[serde(default, skip_serializing_if = "Option::is_none")]
674    pub recovery: Option<Box<planning::PlanningRecoverySnapshot>>,
675}
676
677#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
678#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
679pub struct PlanApprovalRequestedEvent {
680    /// Identifier of the thread emitting the approval request.
681    pub thread_id: String,
682    /// Identifier of the turn that produced the plan.
683    pub turn_id: String,
684    /// Plan file associated with the approval request, when available.
685    #[serde(skip_serializing_if = "Option::is_none")]
686    pub plan_file: Option<String>,
687}
688
689#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
690#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
691#[serde(rename_all = "snake_case")]
692pub enum PlanApprovalDecision {
693    /// Execute with normal per-edit approval prompts.
694    Execute,
695    /// Execute with automatic edit approval enabled.
696    AutoAccept,
697    /// Execute the plan after rebuilding a fresh context.
698    FreshContext,
699    /// Keep planning and revise the proposed plan.
700    Revise,
701    /// Dismiss the approval request without implementing.
702    Cancel,
703    /// Hand the plan to the build primary agent.
704    SwitchBuild,
705    /// Hand the plan to the auto primary agent.
706    SwitchAuto,
707    /// Catch-all for decisions added in newer schema versions.
708    #[serde(other)]
709    Unknown,
710}
711
712#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
713#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
714pub struct PlanApprovalResolvedEvent {
715    /// Identifier of the thread emitting the approval decision.
716    pub thread_id: String,
717    /// Identifier of the turn in which the decision was made.
718    pub turn_id: String,
719    /// Decision selected by the user or active execution policy.
720    pub decision: PlanApprovalDecision,
721    /// Whether the decision came from policy rather than an interactive user action.
722    pub automatic: bool,
723}
724
725#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
726#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
727#[serde(rename_all = "snake_case")]
728pub enum HarnessEventKind {
729    PlanningStarted,
730    PlanningCompleted,
731    ContinuationStarted,
732    ContinuationSkipped,
733    /// A turn was blocked before success could be confirmed. Carries the fuse
734    /// counters so UI layers can render without correlating multiple events.
735    TurnBlocked,
736    /// A bounded tool-free recovery pass was scheduled after blocked calls.
737    BlockedRecoveryStarted,
738    /// A bounded tool-free recovery pass finished.
739    BlockedRecoveryFinished,
740    BlockedHandoffWritten,
741    /// The owning session resolved its archived blocked handoff and removed
742    /// the live recovery pointer.
743    BlockedHandoffResolved,
744    EvaluationStarted,
745    EvaluationPassed,
746    EvaluationFailed,
747    RevisionStarted,
748    EscalationTriggered,
749    EscalationBypassed,
750    VerificationStarted,
751    VerificationPassed,
752    VerificationFailed,
753    /// Agent recovered from a transient error (e.g. after retry succeeded).
754    ErrorRecovered,
755    /// A transient tool failure triggered an automatic retry attempt.
756    ToolRetryAttempted,
757    /// Latency record for a tool execution, emitted on turn completion.
758    ToolLatencyRecorded,
759    /// A checkpoint snapshot was created for the current turn.
760    SnapshotCreated,
761    /// A checkpoint snapshot was restored (rewind operation).
762    SnapshotRestored,
763    /// The user granted additional session tool-call capacity and the
764    /// pending call will be retried in the same turn.
765    ///
766    /// No longer emitted: the per-turn/session tool-call count budget was
767    /// removed. Retained for wire compatibility with older session logs.
768    SessionToolLimitIncreased,
769    /// The user granted additional tool-loop capacity for the current turn.
770    ///
771    /// No longer emitted: the per-turn tool-loop budget was removed.
772    /// Retained for wire compatibility with older session logs.
773    ToolLoopLimitIncreased,
774    /// A background subprocess or exec session reached a terminal state.
775    BackgroundSubprocessCompleted,
776    /// A native delegated agent's public status and ancestry were observed.
777    DelegatedAgentStatus,
778    /// A message was sent to a peer session's mailbox.
779    SessionMessageSent,
780    /// A peer session's message was received from this session's mailbox.
781    SessionMessageReceived,
782    /// A mailbox message expired before delivery.
783    SessionMessageExpired,
784}
785
786#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
787#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
788#[serde(rename_all = "snake_case")]
789pub enum PermissionDecision {
790    Allow,
791    Deny,
792    Cancelled,
793    Followup,
794}
795
796#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
797#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
798pub struct PermissionRequestedEvent {
799    /// Name of the tool that requires permission.
800    pub tool_name: String,
801    /// Identifier of the tool invocation that requested permission, when known.
802    #[serde(default, skip_serializing_if = "Option::is_none")]
803    pub tool_call_id: Option<String>,
804}
805
806#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
807#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
808pub struct PermissionResolvedEvent {
809    /// Name of the tool that was permitted or denied.
810    pub tool_name: String,
811    /// Identifier of the tool invocation whose permission was resolved, when known.
812    #[serde(default, skip_serializing_if = "Option::is_none")]
813    pub tool_call_id: Option<String>,
814    /// User's decision on the permission prompt.
815    pub decision: PermissionDecision,
816    /// Wall-clock time the prompt was visible, in milliseconds.
817    pub wait_ms: u64,
818}
819
820#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
821#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
822#[serde(rename_all = "snake_case")]
823pub enum InterjectionSource {
824    Direct,
825    Queue,
826}
827
828#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
829#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
830#[serde(rename_all = "snake_case")]
831pub enum RedirectKind {
832    Interjection,
833}
834
835#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
836#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
837pub struct InterjectedEvent {
838    /// Public correction text, when recorded by the runtime.
839    #[serde(default, skip_serializing_if = "Option::is_none")]
840    pub text: Option<Box<String>>,
841    /// How the interjection reached the running turn.
842    pub source: InterjectionSource,
843    /// Number of image attachments that accompanied the interjection.
844    pub image_count: u32,
845    /// Always `Interjection` for this event; carried so the shared
846    /// `redirect_kind` field is queryable uniformly across redirect events.
847    pub redirect_kind: RedirectKind,
848}
849
850#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
851#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
852pub struct HarnessEventItem {
853    /// Specific harness event emitted by the runtime.
854    pub event: HarnessEventKind,
855    /// Optional human-readable message associated with the event.
856    #[serde(skip_serializing_if = "Option::is_none")]
857    pub message: Option<String>,
858    /// Optional verification command associated with the event.
859    #[serde(skip_serializing_if = "Option::is_none")]
860    pub command: Option<String>,
861    /// Optional artifact path associated with the event.
862    #[serde(skip_serializing_if = "Option::is_none")]
863    pub path: Option<String>,
864    /// Optional exit code associated with verification results.
865    #[serde(skip_serializing_if = "Option::is_none")]
866    pub exit_code: Option<i32>,
867    /// Retry/recovery attempt number (1-indexed). Only set for retry-related events.
868    #[serde(skip_serializing_if = "Option::is_none")]
869    pub attempt: Option<u32>,
870    /// Canonical error category for retry/recovery events.
871    #[serde(skip_serializing_if = "Option::is_none")]
872    pub error_category: Option<String>,
873    /// Latency in milliseconds for tool-execution latency events.
874    #[serde(skip_serializing_if = "Option::is_none")]
875    pub duration_ms: Option<u64>,
876    /// Stable task identifier for background completion events.
877    #[serde(skip_serializing_if = "Option::is_none")]
878    pub task_id: Option<String>,
879    /// Child session identifier for background completion events; the peer
880    /// session for session-messaging events.
881    #[serde(skip_serializing_if = "Option::is_none")]
882    pub session_id: Option<String>,
883    /// Correlation id linking related harness events (a mailbox question to
884    /// its answer for session-messaging events).
885    #[serde(skip_serializing_if = "Option::is_none")]
886    pub correlation_id: Option<String>,
887    /// Exec-session identifier for background completion events.
888    #[serde(skip_serializing_if = "Option::is_none")]
889    pub exec_session_id: Option<String>,
890    /// Terminal background status, when the event represents a subprocess.
891    #[serde(skip_serializing_if = "Option::is_none")]
892    pub status: Option<String>,
893    /// Archived transcript reference for background completion events.
894    #[serde(skip_serializing_if = "Option::is_none")]
895    pub transcript_path: Option<String>,
896    /// Archived session reference for background completion events.
897    #[serde(skip_serializing_if = "Option::is_none")]
898    pub archive_path: Option<String>,
899}
900
901impl HarnessEventItem {
902    /// A harness event with every optional field unset. Prefer this over a
903    /// struct literal so new optional fields do not break construction sites.
904    #[must_use]
905    pub fn new(event: HarnessEventKind) -> Self {
906        Self {
907            event,
908            message: None,
909            command: None,
910            path: None,
911            exit_code: None,
912            attempt: None,
913            error_category: None,
914            duration_ms: None,
915            task_id: None,
916            session_id: None,
917            correlation_id: None,
918            exec_session_id: None,
919            status: None,
920            transcript_path: None,
921            archive_path: None,
922        }
923    }
924}
925
926#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
927#[cfg_attr(feature = "schema-export", derive(schemars::JsonSchema))]
928pub struct ErrorItem {
929    /// Error message displayed to the user or logs.
930    pub message: String,
931}
932
933#[cfg(test)]
934mod tests;